Reputation: 13
So my code should look through a text file via command line with
./program < text.txt
This way of executing the program is important for my purposess.
but after going through it once every other method already looks at the end of the text file.
Im trying to go through a provided text file but once a function reads it once, probably the pointer already stays at the end of the file and other functions dont work anymore.
So there is the most basic function that uses this. Once i try any other function with the same for cycle it just doesnt work anymore. I suppose its the pointer but i havent been successful with finding a way to refresh it.
void writeOut()
{
char line[100];
for(; fgets(line, 100, stdin) != NULL;)
{
fprintf(stdout,"%s", line);
}
fprintf(stdout,"\n");
}
I expect to be able to read through the same file multiple times and be able to "flush" the memory of fgets().
Thanks for any useful input
Upvotes: 1
Views: 2986
Reputation: 212248
If stdin is a seekable file, then rewind(stdin)
ought to work just fine. If you need to rewind on a non-seekable file, then you either need to buffer all the data (either in memory or in a temporary file) or abort. That is, just do:
if( fseek(stdin, 0L, SEEK_SET) ) {
perror("stdin");
exit(EXIT_FAILURE);
}
Upvotes: 1
Reputation: 180256
The rewind()
and fseek()
functions are the conventional ways to reposition a stream that supports doing so. Not all streams do support it, and whether yours does is a function not only of your C implementation but also of your operating environment and the specific circumstances of program launch.
I would generally be inclined to expect a stream associated with redirected input not to support repositioning, so even if it worked in your particular circumstances, you would be wise to consider a more reliable alternative.
In particular, you could create a temporary file, copy the standard input to it, and then use that file. You can perform the copying either ahead of time or as you perform the first ordinary run-through. If you need to re-read the data specifically from stdin
, as opposed to from some other stream you open, then you can use freopen()
to attach stdin
to your temp file.
Upvotes: 5