Previous Page
Next Page


Moves the access position in a file

#include <stdio.h>
int fseek ( FILE *fp , long offset , int origin  );

The fseek( ) function moves the file position indicator for the file specified by the FILE pointer argument. The new position is offset bytes from the position selected by the value of the origin argument, which may indicate the beginning of the file, the previous position, or the end of the file. Table 17-2 lists the permitted values for origin.

Table 17-2. Values for fseek( )'s origin argument

Value of origin

Macro name

Offset is relative to



The beginning of the file



The current position



The end of the file

You can use a negative offset value to move the file access position backward, but the position indicator cannot be moved backward past the beginning of the file. However, it is possible to move the position indicator forward past the end of the file. If you then perform a write operation at the new position, the file's contents between its previous end and the new data are undefined.

The fseek( ) function returns 0 if successful, or -1 if an error occurs.


typedef struct {  long id;
                  double value;
               } record;
FILE *fp;
record cur_rec = (record) { 0, 0.0 };
int reclength_file = sizeof(record);
long seek_id = 123L;

if ((fp = fopen("records", "r")) == NULL)
  perror( "Unable to open records file" );
else do
  if ( 1 > fread( &, sizeof (long), 1, fp ))
    fprintf( stderr, "Record with ID %ld not found\n", seek_id );
  else      // Skip rest of record
    if ( fseek( fp, reclength_file - sizeof(long), 1 )
      perror( "fseek failed" );
} while ( != seek_id );

See Also

fgetpos( ), fsetpos( ), ftell( ), rewind( )

Previous Page
Next Page