C Programming/C Reference/stdio.h/fseek

< C Programming < C Reference < stdio.h

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

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:

Return value

The return value is an integer which mean:

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

Example

#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);
  fclose(file_handle);
  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

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.