fseek

Changes the file position indicator of a stream.

Library:LibC
Classification:ANSI
Service:File and Directory I/O

Syntax

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

Parameters

fp

(IN) Points to the file.

offset

(IN) Specifies the file position to seek. For a text stream, the offset must be either zero or the value returned by an earlier successful call ftell.

whence

(IN) Specifies the relative file position and uses one of the following flags:

Flag

Value

Description

SEEK_SET

0

Add the offset parameter to the beginning of the file. This is the only acceptable value on a text stream and must be set to this flag when offset uses a value returned by ftell.

SEEK_CUR

1

Add the offset parameter to the current position in the binary file.

SEEK_END

2

Add the offset parameter to the end of the binary file.

Return Values

If successful, returns 0. Otherwise, returns -1 and sets errno to one of the following:

Decimal

Constant

Description

4

EBADF

The file descriptor is not valid.

9

EINVAL

The whence argument is invalid.

24

EAGAIN

The O_NONBLOCK flag is set for the file descriptor, and the process cannot immediately perform the operation.

25

ENXIO

A request was made of a nonexistent device, or the request was outside the capabilities of the device.

28

EIO

A physical I/O error has occurred.

32

EPIPE

An attempt is made to write to a pipe or FIFO that is not open for reading by any process.

33

ESPIPE

The file descriptor is associated with a pipe or FIFO.

63

EINTR

A signal interrupted the read operation.

71

EFBIG

An attempt was made to write to a file that exceeds the maximum file size.

81

EOVERFLOW

The resulting file offset cannot be represented correctly in an object of type long.

Remarks

The fseek function changes the read/write position of the file specified by fp. This position defines the character to be read or written on the next I/O operation on the file. The fp parameter is a file pointer returned by fopen or freopen. The offset parameter is the position to seek, relative to one of three positions specified by the whence parameter.

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

When operating on a text file, you can only set the whence parameter to SEEK_SET and you can only set the offset parameter to 0 or a value obtained from ftell. Any other combinations have indeterminate results. You can restore a position by using the value returned by ftell in a subsequent call to fseek with the whence parameter set to SEEK_SET.

See Also