How to receive input data from a C program from a file?

Asked

Viewed 158 times

4

I have a program in C. Let’s assume that its name compiled is a.out (pattern).

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 the function main even)?

1 answer

3


Basically what you need to do is read the stdin which is where the archive 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);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

So whatever comes through pipe operating system will be printed on the screen. The pipe will take a data source, may be a file but may be another source as well.

  • Thanks for the reply. I tested, but did not print anything. So I removed the if, I compiled and tried to run again but gives an error: Segmentation fault (core dumped)

  • I made a change, I had eaten ball, I could do something simpler. I still can’t guarantee that it’s okay because I have no way to test it here but if it doesn’t work out, tell me the problem that I try to solve.

  • Now it worked out! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.