Rewinding a FILE pointer

I'm writing a program to read some information (irrelevant for this question) from a file. To reach this information, I have used quite a few fseek()'s, since there's a lot of stuff between the beginning of the file and what I want. However, the information being searched for is manually inputted by the user, so typo's are possible.

I am aware of rewind(), but would like to, instead, have a pointer stay at the beginning of the potentially-relevant section of the file while another pointer runs through the file itself. That way, should there have been a typo, the moving pointer can simply return to the value of the initial pointer.

However, should I do
1
2
3
FILE* mem = f; //f has already been assigned the open file
/*lots of fseek()'s*/
f=mem;

It doesn't work. Following the steps, I can see that even though all the fseek()'s are only applied to f, the contents of mem also move. I have also tried using const FILE* mem=f, but the mem pointer still moves. I have also tried FILE* mem = *f and FILE* mem = &f, which didn't work for obvious reasons.

How can I make mem's values not change while f's do?
Low level file classes do not work like that, and certainly not standard buffered I/O classes.

If you want to do that sort of thing, you need to build a higher level file class that uses a more simple existing class in it's implementation.

Assigning FILE* m = f; doesn't make a new copy of the FILE instance. Have you thought about the implications if it did? For example, what do you think should happen with the extra file handle?
I am aware that it wouldn't make a new copy of the FILE, but that's also not my intent.

In the following example file (imagine that the beginning of the file is a few dozen thousand lines above this passage):
1 2 3 4 5
f would begin before 1, as would mem. However, should I then do fseek(f,4,SEEK_CUR), f would move to before 3. In practice, as I am currently doing, so does mem. However, is it not possible for mem to remain before 1, so that f can then jump back to that position? Basically, is it not possible to partially rewind a file pointer?

Though I do suppose there is a more-than-valid point to be made regarding what would happen should I then insert a fclose(f) in the code followed by manipulations of mem.

Hrmph.
Last edited on
In a word, no.

FILE supports one file pointer. However, you can move it with fseek (as you already know) and find out where you are with ftell (as you probably already know too). If you've moved the file pointer, it's been moved.

If you're doing a lot of this, and if your operating system supports it, you could map the file into memory and use multiple (memory) pointers into the file.
Topic archived. No new replies allowed.