How do I use fscanf from the beginning each time when I am in a for loop?
I want to do something like this:
for(i=0; i<5; i++)
while(fscanf(in, "%d", &number)
.......
Basically, when I use fscanf the first time, it starts scanning from the beginning of the file. I want it to start working from the beginning each time a for loop has been completed, how can I do that?
Use rewind()
to seek back to the beginning of the file:
for (i = 0; i < 5; i++) {
rewind(in);
while (fscanf(in, "%d", &number)
.......
Note however that this solution only works if the stream is seekable. If it is bound to a regular file, either opened by fopen
or from a shell redirection, it should be seekable, but if it is bound to a terminal, a pipe or some other character device, rewind()
may fail. You cannot test this with rewind()
, but here is an alternative:
if (fseek(in, 0L, SEEK_SET)) {
fprintf(stderr, "cannot rewind inut stream\n");
exit(1);
}
A more reliable approach would be to save the values read by fscanf()
to avoid seeking.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.