Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between fgetpos/fsetpos and ftell/fseek

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()?

like image 200
carlfilips Avatar asked Jul 27 '10 22:07

carlfilips


People also ask

What is Fseek and Ftell in C?

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 )

How does Fgetpos work in C?

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.


1 Answers

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 an fpos_t object whose value shall have been previously obtained by a call to fgetpos.

(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.

like image 200
HughHughTeotl Avatar answered Sep 19 '22 23:09

HughHughTeotl