Documentation Center

  • Trials
  • Product Updates

fseek

Move to specified position in file

Syntax

fseek(fileID, offset, origin)
status = fseek(fileID, offset, origin)

Description

fseek(fileID, offset, origin) sets the file position indicator offset bytes from origin in the specified file.

status = fseek(fileID, offset, origin) returns 0 when the operation is successful. Otherwise, it returns -1.

Input Arguments

fileID

Integer file identifier obtained from fopen.

offset

Number of bytes to move from origin. Can be positive, negative, or zero. The n bytes of a given file are in positions 0 through n-1.

origin

Starting location in the file:

'bof' or -1

Beginning of file

'cof' or 0

Current position in file

'eof' or 1

End of file

Examples

Copy 5 bytes from the file test1.dat, starting at the tenth byte, and append to the end of test2.dat:

% Create files test1.dat and test2.dat
% Each character uses 8 bits (1 byte)

fid1 = fopen('test1.dat', 'w+');
fwrite(fid1, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');

fid2 = fopen('test2.dat', 'w+');
fwrite(fid2, 'Second File');

% Seek to the 10th byte ('J'), read 5
fseek(fid1, 9, 'bof');
A = fread(fid1, 5, 'uint8=>char');
fclose(fid1);

% Append to test2.dat
fseek(fid2, 0, 'eof');
fwrite(fid2, A);
fclose(fid2);

Alternatives

To move to the beginning of a file, call

frewind(fileID)

This call is identical to

fseek(fileID, 0, 'bof')

See Also

| | | | | | | | |

Was this topic helpful?