Fortran Library Reference

fseek, ftell: Determine Position and Reposition a File

fseek and ftell are routines that permit repositioning of a file. ftell returns a file's current position as an offset of so many bytes from the beginning of the file. At some later point in the program, fseek can use this saved offset value to reposition the file to that same place for reading.

fseek: Reposition a File on a Logical Unit

The function is called by:

INTEGER*4 fseek

n = fseek( lunit, offset, from )

lunit

INTEGER*4

Input  

Open logical unit  

offset

INTEGER*4

or

INTEGER*8

Input  

Offset in bytes relative to position specified by from

An INTEGER*8 offset value is required when compiled for a 64-bit environment, such as Solaris 7, with -xarch=v9. If a literal constant is supplied, it must be a 64-bit constant, for example: 100_8

from

INTEGER*4

Input  

0=Beginning of file  

1=Current position  

2=End of file  

Return value 

INTEGER*4

Output  

n=0: OK; n>0: System error code


Note -

On sequential files, following a call to fseek by an output operation (e.g. WRITE) causes all data records following the fseek position to be deleted and replaced by the new data record (and an end-of-file mark). Rewriting a record in place can only be done with direct access files.


Example: fseek()--Reposition MyFile to two bytes from the beginning


    INTEGER*4 fseek, lunit/1/, offset/2/, from/0/, n
    open( UNIT=lunit, FILE='MyFile' )
    n = fseek( lunit, offset, from )
    if ( n .gt. 0 ) stop 'fseek error'
    end

:

Example: Same example in a 64-bit environment and compiled with -xarch=v9:


    INTEGER*4 fseek, lunit/1/,  from/0/, n 
    INTEGER*8 offset/2/
    open( UNIT=lunit, FILE='MyFile' )
    n = fseek( lunit, offset, from )
    if ( n .gt. 0 ) stop 'fseek error'
    end

ftell: Return Current Position of File

The function is called by:

INTEGER*4 ftell

n = ftell( lunit )

lunit

INTEGER*4

Input  

Open logical unit  

Return value 

INTEGER*4

or

INTEGER*8

Output  

n>=0: n=Offset in bytes from start of file

n<0: n=System error code

An INTEGER*8 offset value is returned when compiling for a 64-bit environment, such as Solaris 7, with -xarch=v9. ftell and variables receiving this return value should be declared INTEGER*8.

Example: ftell():


    INTEGER*4 ftell, lunit/1/, n
    open( UNIT=lunit, FILE='MyFile' )
    ... 
    n = ftell( lunit )
    if ( n .lt. 0 ) stop 'ftell error'
    ...

Example: Same example in a 64-bit environment and compiled with -xarch=v9:


    INTEGER*4 lunit/1/
    INTEGER*8 ftell, n
    open( UNIT=lunit, FILE='MyFile' )
    ... 
    n = ftell( lunit )
    if ( n .lt. 0 ) stop 'ftell error'
    ...

See also fseek(3S) and perror(3F); also fseeko64(3F) ftello64(3F).