mattssoncode
mattssoncode

Reputation: 111

Is there a way to set the file pointer back to the start of the current row?

I would like to check that the formatting of a file is correct, using fscanf, like this.

fscanf(fp, "%c%d %d %c%d", &ch, &a, &b, &ch2, &c);

Is there a way to get the file pointer back to the start of the current line after using this fscanf? Is fseek a possible solution? if so, how?

Upvotes: 1

Views: 995

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51894

Is there a way to get the file pointer back to the start of the current line after using this fscanf? Is fseek a possible solution? if so, how?

Yes, there is! You can call the ftell() function before fscanf and then use fseek to restore to the saved location:

long int savePos = ftell(fp);                       // save current location
fscanf(fp, "%c%d %d %c%d", &ch, &a, &b, &ch2, &c);  // do the test read
//.. do something to check your input...
fseek(fp, savePos, SEEK_SET);                       // restore position

See cppreference for further information on the ftell function, but note:

For text streams, the numerical value may not be meaningful but can still be used to restore the position to the same position later using fseek (if there are characters put back using ungetc still pending of being read, the behavior is undefined).

Upvotes: 4

Related Questions