Search code examples
cfileshellstdingetchar

C - reading from stdin with a file?


So I have a text file that I'm using in the same directory as my C program and I'm using MinGW as the compiler. This is my input:

./program "hello" > helloworld.txt

In my program in the main function, I have:

#include <stdio.h>
int main(int argc, char *argv[]) {
char c;
while ((c=getchar()) != EOF) {
printf("test\n");
}
return 0;
}

Nothing is printing. The text file definitely has lines in it. I don't know what's going on. This assignment voids the use of fopen() and all that. It is getchar() and stdin only.


Solution

  • Your command isn't reading from the text file, it's writing to it. If you want to read from it, you need to do this:

    ./program < helloworld.txt
    

    helloworld.txt:

    this
    is a
    test
    

    Output:

    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test