What's the difference between using the functions fgetpos()
and fsetpos()
and using the functions ftell()
and fseek()
to get and set a position in a file?
What are fgetpos()
and fsetpos()
good for? Why would they be used instead of ftell()
and fseek()
?
ftell() is used to store the current file position. fseek() is used to relocate to one of the following: A file position stored by ftell() A calculated record number ( SEEK_SET ) A position relative to the current position ( SEEK_CUR )
The fgetpos() function determines the current value of the file position indicator in an open file, and places the value in the variable referenced by the pointer argument ppos . You can use this value in subsequent calls to fsetpos() to restore the file position.
None of the above answers are correct - in fact if you use fsetpos
interchangeably with fseek
you could introduce a security flaw (https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=20087255).
The reason is that the fpos_t *pos
argument to fsetpos
isn't actually an integer so it can't be used to seek to arbitrary locations in a file. The only valid values are therefore ones obtained from fgetpos
. As the docs say,
The internal file position indicator associated with stream is set to the position represented by
pos
, which is a pointer to anfpos_t
object whose value shall have been previously obtained by a call tofgetpos
.
(http://www.cplusplus.com/reference/cstdio/fsetpos/)
If all you want is the ability to seek to arbitrary locations beyond 32-bit boundary, then use ftello
/ fseeko
and compile with #define _FILE_OFFSET_BITS 64
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With