Thursday, August 13, 2009

fseek

Set file position indicator

Syntax

  • status = fseek(fid,offset,origin)

Description

status = fseek(fid,offset,origin) repositions the file position indicator in the file with the given fid to the byte with the specified offset relative to origin.

For a file having n bytes, the bytes are numbered from 0 to n-1. The position immediately following the last byte is the end of the file, or eof, position. You would seek to the eof position if you wanted to add data to the end of a file.

This figure represents a file having 12 bytes, numbered 0 through 11. The first command shown seeks to the ninth byte of data in the file. The second command seeks just past the end of the file data, to the eof position.

fseek does not seek beyond the end of file, eof, position. If you attempt to seek beyond eof, MATLAB returns an error status.

Arguments


fid
An integer file identifier obtained from fopen.
offset
A value that is interpreted as follows:

offset > 0
Move position indicator offset bytes toward the end of the file.

offset = 0
Do not change position.

offset <>
Move position indicator offset bytes toward the beginning of the file.
origin
A string whose legal values are:

'bof'
-1: Beginning of file.

'cof'
0: Current position in file.

'eof'
1: End of file.
status
A returned value that is 0 if the fseek operation is successful and -1 if it fails.

Examples

This example opens the file test1.dat, seeks to the 20th byte, reads fifty 32-bit, unsigned integers into variable A, and closes the file. It then opens a second file, test2.dat, seeks to the end-of-file position, appends the data in A to the end of this file, and closes the file.

  • fid = fopen('test1.dat', 'r');
    fseek(fid, 19, 'bof');
    A = fread(fid, 50, 'uint32');
    fclose(fid);

    fid = fopen('test2.dat', 'r+');
    fseek(fid, 0, 'eof');
    fwrite(fid, A, 'uint32');
    fclose(fid);

No comments:

Post a Comment