How to receive the input data of a program in C from a file?

3

I have a program in C. Let's assume its compiled name is a.out (default).

When I use the following command to execute it ...

./a.out < arquivo.txt

... how do I read the content of arquivo.txt within the program (in function main same)?

    
asked by anonymous 06.04.2015 / 14:49

1 answer

3

Basically what you need to do is read the stdin which is where the file data will come from. A simplified implementation would be this:

#include <stdlib.h>
#include <stdio.h>

#define BUFF_SIZE 1024

int main(void) {
    char buffer[BUFF_SIZE];
    while (fgets(buffer, BUFF_SIZE, stdin) != NULL) {
        printf("%s", buffer);
    }
    return 0;
}

In this way whatever comes through the pipe of the operating system will be printed on the screen. The pipe will fetch a data source, it may be a file but may be another source as well.

    
06.04.2015 / 15:01