Development Environment    

Controlling Position in a File

Once you open a file with fopen, MATLAB maintains a file position indicator that specifies a particular location within a file. MATLAB uses the file position indicator to determine where in the file the next read or write operation will begin. The following sections describe how to

Determining End-of-File

The fseek and ftell functions let you set and query the position in the file at which the next input or output operation takes place:

The syntax for fseek is

fid is the file identifier for the file. offset is a positive or negative offset value, specified in bytes. origin is one of the following strings that specify the location in the file from which to calculate the position.

'bof'
Beginning of file
'cof'
Current position in file
'eof'
End of file

Understanding File Position

To see how fseek and ftell work, consider this short M-file.

This code writes out the numbers 1 through 5 to a binary file named five.bin. The call to fwrite specifies that each numerical element be stored as a short. Consequently, each number uses two storage bytes.

Now reopen five.bin for reading.

This call to fseek moves the file position indicator forward 6 bytes from the beginning of the file.

This call to fread reads whatever is at file positions 7 and 8 and stores it in variable four.

The act of reading advances the file position indicator. To determine the current file position indicator, call ftell.

This call to fseek moves the file position indicator back 4 bytes.

Calling fread again reads in the next value (3).


  Writing Binary Data Reading Strings Line by Line from Text Files