使用C在<终端中给出时读取文件字节

0 c unix terminal

我看了很多,找不到这个,我敢肯定我在寻找错误的东西.

无论如何,我需要读取终端中给出的文件并输出字节码.如果我手动输入文件名作为char*,我可以很容易地做到这一点,但我不知道如何开始这个.

一个示例将在linux终端中: $./a.out <test.exe

它应该将test.exe打印到终端作为字节码.预先感谢您的任何帮助.

pmg*_*pmg 5

使用命令行重定向,程序stdin用于读取和stdout写入.

编译并运行它,例如:
./a.out < source.c,或./a.out < source.c > source.upper,...

#include <ctype.h>
#include <stdio.h>
int main(void) {
    int ch;
    while ((ch = getchar()) != EOF) {
        putchar((unsigned char)ch);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果要将文件名指定为命令行参数,则可以使用argv获取文件名,例如,例如./a.out filename.txt

#include <stdio.h>
int main(int argc, char **argv) {
    if (argc > 1) {
        printf("processing %s\n", argv[1]);
    } else {
        printf("no command line parameter given.\n");
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)