C Programming/stdio.h/fseek

From Wikibooks, open books for an open world
Jump to: navigation, search

fseek is a C function belonging to the ANSI C standard library, and included in the file stdio.h. Its purpose is to change the file position indicator for the specified stream. Because fseek uses 32 bit values on many platforms it has a limitation of maximum 2 gigabyte seeks. fseeko64 would be used for larger offsets.

Function prototype[edit]

int fseek(FILE *stream_pointer, long offset, int origin);

The fseek function moves the file pointer associated with the stream to a new location that is offset bytes from origin

Argument meaning:

  • stream_pointer is a pointer to the stream FILE structure of which the position indicator should be changed;
  • offset is a long integer which specifies the number of bytes from origin where the position indicator should be placed;
  • origin is an integer which specifies the origin position. It can be:
    • SEEK_SET: origin is the start of the stream
    • SEEK_CUR: origin is the current position
    • SEEK_END: origin is the end of the stream

Return value[edit]

The return value is an integer which mean:

  • 0 (zero) : function performed successfully in the stream
  • nonzero : an error occurred
  • On devices incapable of seeking, the return value is undefined.

Note that each error number has a distinct meaning. The meaning can be revealed by checking errno.h.


#include <stdio.h>

int main(int argc, char **argv) {
  FILE *file_handle;
  long int file_length;
  file_handle = fopen("file.bin","rb");
  if(fseek(file_handle, 0, SEEK_END)) {
    puts("Error while seeking to end of file");
    return 1;
  file_length = ftell(file_handle);
  if (file_length < 0) {
    puts("Error while reading file position");
    return 2;
  printf("File length: %d bytes\n", file_length);
  return 0;

This program code opens a file called file.bin in read-only mode. The length of the file is determined by seeking to the end and then reading back the position of the file pointer.

External links[edit]