fseek

 

Description

Moves the file pointer (if any) associated with stream to a new location that is offset bytes from origin.

Syntax

int fseek( FILE * stream, long offset, int origin )

Parameters

stream
Pointer to FILE
offset
Number of bytes from origin
origin
Initial position

Return

If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable of seeking, the return value is undefined.

Examples

EX1

//The following example open the file fseek.out and moves the pointer to the file's beginning

void test_fseek()
{
    FILE *stream;
    char line[81];
    int  result;
    
    stream = fopen( "fseek.out", "w+" );
    if( stream == NULL )
        printf( "The file fseek.out was not opened\n" );
    else
    {
        fprintf( stream, "The fseek begins here: "
                       "This is the file 'fseek.out'.\n" );
        result = fseek( stream, 23L, SEEK_SET);
        if( result )
            printf( "Fseek failed" );
        else
        {
            printf( "File pointer is set to middle of first line.\n" );
            fgets( line, 80, stream );
            printf( "%s", line );
        }
        fclose( stream );
    }
}

Remark

The fseek function moves the file pointer (if any) associated with stream to a new location that is offset bytes from origin. The next operation on the stream takes place at the new location. On a stream open for update, the next operation can be either a read or a write. The argument origin must be one of the following constants, defined in COMMON.H:

SEEK_CUR :Current position of file pointer

SEEK_END :End of file

SEEK_SET :Beginning of file

You can use fseek to reposition the pointer anywhere in a file. The pointer can also be positioned beyond the end of the file. fseek clears the end-of-file indicator and negates the effect of any prior ungetc calls against stream.

When a file is opened for appending data, the current file position is determined by the last I/O operation, not by where the next write would occur. If no I/O operation has yet occurred on a file opened for appending, the file position is the start of the file.

For streams opened in text mode, fseek has limited use, because carriage return, linefeed translations can cause fseek to produce unexpected results. The only fseek operations guaranteed to work on streams opened in text mode are:

  • Seeking with an offset of 0 relative to any of the origin values.
  • Seeking from the beginning of the file with an offset value returned from a call to ftell.

See Also

ftell

header to Include

origin.h

Reference