fseek

Purpose

Positions the file pointer in a file.

Format

ret = fseek(fh, offs, base)
Parameters:
  • fh (scalar) – file handle of a file opened with fopen().

  • offs (scalar) – offset (in bytes).

  • base (scalar) –

    base position.

    0

    beginning of file.

    1

    current position of file pointer.

    2

    end of file.

Returns:

ret (scalar) – 0 if successful, 1 if not.

Remarks

The fseek() procedure moves the file pointer offs bytes from the specified base position. offs can be positive or negative. The call may fail if the file buffer needs to be flushed (see fflush()).

If fseek() fails, you can call fstrerror() to find out why.

For files opened for update (see fopen()), the next operation can be a read or a write.

The fseek() procedure is not reliable when used on files opened in text mode (see fopen()). This has to do with the conversion of carriage return-linefeed sequences to newlines. In particular, an fseek() that follows one of the fgetxxx or fputxxx commands may not produce the expected result.

For example:

p = ftell(f);
s = fgetsa(f, 7);
call fseek(f, p, 0);

is not reliable. We have found that the best results are obtained by using fseek() to navigate to the beginning of the file and then using fseek() navigate to the desired location, as in

p = ftell(f);
s = fgetsa(f, 7);
call fseek(f, 0, 0);
call fseek(f, p, 0);

If you pass fseek() the handle of a file opened with open (i.e., a data set or matrix file), your program will terminate with a fatal error.

See also

Functions fopen()