Robert
Robert

Reputation: 3

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.

Upvotes: 0

Views: 1925

Answers (4)

Platinum Azure
Platinum Azure

Reputation: 46183

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. :-)

Upvotes: 0

pmg
pmg

Reputation: 108978

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;
}

Upvotes: 5

MByD
MByD

Reputation: 137312

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.

Upvotes: 0

Santiago Alessandri
Santiago Alessandri

Reputation: 6855

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.

Upvotes: 1

Related Questions