Saving off the current read position so I can seek to it later

c, io, scanf

Solution

Use the ftell() function. It will return the offset in the file.

unsigned long position = ftell(file);

However, with text files, it is very important to know that ftell() can report the wrong position unless the internal buffer has been cleared. To do this,

unsigned long position;
fflush(file);
position = ftell(file);

Later, you can use fseek

fseek(file,position,SEEK_SET);

ftell() told use the offset from the beginning of the file earlier. Here, you use SEEK_SET to indicate that the position you're passing is from the beginning of the file.

EDIT: Richard asked what fflush() does. When you are reading or writing a file, the C library is almost always keeping a buffer of the information. To "flush" that buffer is to write it out to disk, to save any changes. Because of the way the C library is allowed to treat text files, it is possible that this buffer can cause ftell() to report the wrong position unless the buffer is flushed. That is what fflush() does.

Problem

I have a program that reads a text file which has a known structure. For example, I have two integers and one string on each line of the file. When I use `fscanf` inside a loop, I can regain `n` structures such as I mentioned above. How do I get my current position in the data file, so I store it somewhere, and then later continue reading my text file from where I left off earlier.

Original source