while( fscanf( tracefile, "%s ", opcode ) != EOF ){blah}
Occasionally I need to cause fscanf to re-read a line upon a certain condition in my code being met. Is this possible; how would I do that?
Thanks.
while( fscanf( tracefile, "%s ", opcode ) != EOF ){blah}
Occasionally I need to cause fscanf to re-read a line upon a certain condition in my code being met. Is this possible; how would I do that?
Thanks.
Assuming your input file is seekable (and not, for example, a pipe or network stream) you could do something like:
fgetpos(tracefile, &position_before);
fscanf( tracefile, "%s ", opcode );
if (need_to_rescan) { fsetpos(tracefile, position_before); }
Backing up and rescanning could be pretty inefficient (as well as the issues of not supporting input from a pipe etc.), so you might want to consider if there's an alternative.
I almost never use fscanf
directly since it's a pain to know where the file pointer is left on an error condition.
I use fgets
to pull in a single line, then I can use sscanf
to my heart's content without having to go back to the file to re-read.