[Previous]
[Contents]
[Next]

fseek()

change the read/write position of a file

Synopsis:

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

Description:

The fseek() function changes the read/write position of the file specified by fp. This position defines the character that will be read or written on the next I/O operation on the file. The argument fp is a file pointer returned by fopen() or freopen(). The argument offset is the position to seek to, relative to one of three positions specified by the argument where. Allowable values for where are:

SEEK_SET
The new file position is computed relative to the start of the file. The value of offset must not be negative.
SEEK_CUR
The new file position is computed relative to the current file position. The value of offset may be positive, negative or zero.
SEEK_END
The new file position is computed relative to the end of the file.

The fseek() function clears the end-of-file indicator, and undoes any effects of the ungetc() function on the same file.

The ftell() function can be used to obtain the current position in the file before changing it. The position can be restored by using the value returned by ftell() in a subsequent call to fseek() with the where parameter set to SEEK_SET.

Returns:

0
Success
Nonzero
An error occurred. errno is set to indicate the error.

Examples:

The size of a file can be determined by the following example, which saves and restores the current position of the file:

#include <stdio.h>

long int filesize( FILE *fp )
  {
    long int save_pos, size_of_file;

    save_pos = ftell( fp );
    fseek( fp, 0L, SEEK_END );
    size_of_file = ftell( fp );
    fseek( fp, save_pos, SEEK_SET );
    return( size_of_file );
  }

void main()
  {
    FILE *fp;

    fp = fopen( "file", "r" );
    if( fp != NULL ) {
      printf( "File size=%ld\n", filesize( fp ) );
      fclose( fp );
    }
  }

Classification:

ANSI

Safety:
Interrupt handler No
Signal handler No
Thread Yes

See also:

errno, fgetpos(), fopen(), fsetpos(), ftell()


[Previous]
[Contents]
[Next]