开发者

Reading a file bytes when given as < in terminal using C

I've looked extensively and can't find this, I'm sure I am searching for the wrong thing.

Anyway, I need to read in a file given in terminal and output the byte code. I can do this easily enough if I manually enter the file name as a char*, but I have no idea how to even开发者_运维百科 start with this.

A sample would be in the linux terminal: $./a.out <test.exe

And it should print to the terminal the test.exe as byte code. Thank you in advance for any help.


With command line redirections, the program uses stdin for reading and stdout for writing.

Compile and run this with, for example:
./a.out < source.c, or ./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;
}

If, on the other hand, you want to specify the filename as a command line parameter, you can use argv to get the filename, as in, for example ./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;
}


With the "<" operator in bash what you do is redirect the stdin, that instead of being the terminal is the given file.

So to read a byte you should only do getchar(). And then you can do whatever you want with it. You will receive an EOF when the file is over.


When you redirect input using < you actually gives the content of the file as standard input and you can treat it as such, meaning you don't need to open a file, but to use getchar() for example to read the content.


When you use file redirection in a shell, the file is piped into standard input. So you can just read from standard input using getchar (or similar) as you normally would.

Your program has no way (in standard C) to know if it's being fed a file or not, or if it's running interactively in a terminal. The best thing to do is just don't think about it. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜