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.
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.
Use ftell to store the position of the file an fseek to go back to it later.
The process is simple with ftell
and fseek
. See the sample code
int i, int1, int2;
FILE *file;
char *str1;
...
// read 10 lines
for(i=0; i<10; i++){
fscanf(file, "%d %d %s", int1, int2, str1);
}
// save the position;
pos = ftell(file);
// close the file
fclose(file)
...
// later go to that same location after opening the same file
fseek(file, pos, 0);
// continue reading
fscanf(file, "%d %d %s", int1, int2, str1);
If I understand correctly, you are looking for ftell function
Doing a fflush
before ftell
to get a file position before reading a record, screws up which record comes next. In my application, just ftell
and later fseek
are working for me.
My mistake was to try using fsetpos
instead of fseek
. The arguments to the former are strange and by forcing the ftell
output into it caused my application to quit right away (not with a fault, but apparently an EOF I wasn't expecting so soon).