I input a text file into my C program by using the <
I/O redirection in the terminal:
MyProgram.exe < "data.txt"
And then use getchar()
and scanf()
in my code to read from the redirected input. However, as this is a redirected file, I can't use a C file pointer to rewind the buffer.
(I want to count the number of lines in a file of an arbitrary size so I can initialize an array, then I want to re-read the file using getchar()
and/or scanf()
).
How do I achieve a rewind or flush when using redirected input?
However, as this is a redirected file, I cant use a c file pointer to rewind the buffer.
Sure you can! And it's really easy. When a file is being redirected to standard input, stdin
is a file, so you can treat it just like any other file:
rewind(stdin);
But keep in mind that this will only work if standard input is being redirected from a file. It won't work if standard input is from the terminal or a pipe (e.g, cat file.txt | myapp
).