Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Aug 18, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Repositioning a File Pointer

The fseek() function provides random file access. It's declared in <stdio.h> as follows:

int fseek(FILE *fstream, int offset, int whence);

The function sets the file pointer associated with fstream to a new position that is offsetbytes from the location specified by whence. The argument whence can have one of these values:

SEEK_SET // file's beginning
SEEK_CUR // current file position
SEEK_END // end of file

In the following example, fseek() is used to calculate a file's size in a portable manner:

long file_size (FILE *f);
 long cur_pos, length;
 cur_pos = ftell(f)
 fseek(f, 0, SEEK_END); // set pointer to end of file
 length=ftell(f); // offset in bytes from file's beginning
 fseek(f, cur_pos, SEEK_SET); // restore original position
 return length;
Danny Kalev
Thanks for your registration, follow us on our social networks to keep up-to-date