Saving/duplicating a file pointer/descriptor

1.6k views Asked by At

I have a requirement where in there is a global FILE pointer/descriptor. One of the functions will read from this pointer/descriptor. The internal pointer associated with the FILE pointer/descriptor advances. After this function returns, I want to read from the same FILE pointer/descriptor and also the same data as the other function read.

But I cant read the same exact data, as the internal pointer has advanced. Duplicating the descriptor doesn't work as the duplicate mirrors the original. Saving the FILE pointer before read also doesn't work as it is a pointer and will again start referring to the same thing.

One alternative is to save the file position using fgetpos() before read and use fsetpos() before the next read.

But this works for file pointers and not descriptors.

With normal pointers its so easy. But things get difficult with FILE pointers.

Are there any other non-clumsy methods of achieving this?

3

There are 3 answers

0
John Bode On

Based on your description, I would hide that file pointer behind another interface that buffers the last-read chunk of data, so that different areas of the code can access the same data without having to rewind the stream.

1
FatalError On

If you are referring to POSIX file descriptors, it sounds like you're looking for lseek().

off_t off;

off = lseek(fd, 0, SEEK_CUR); /* get current offset */
/* do some read(s) */
lseek(fd, off, SEEK_SET);
0
dwalter On

another option would be to memory-map the file using mmap().

This will allow you to randomly read any position within the file without having to use lseek() or fseek().

you'll find a short tutorial on mmap() at linuxquestions