Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

fseek

Move to specified position in file

Syntax

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

Description

example

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

status = fseek(___) returns 0 when the operation is successful. Otherwise, fseek returns -1. Use any of the previous input argument combinations.

Examples

collapse all

Open the following badpoem.txt file and perform read operations (which advance the position pointer) and then use seek to move to a new position in the file.

Use fopen to open the file. Then, use ftell to query the current position.

fid = fopen('badpoem.txt');
ftell(fid)
ans = 0

Read the first three lines and query the position in the file after each read. Use fgetl to read and fseek to examine the current position after the read operation.

tline1 = fgetl(fid)  % read the first line 
tline1 = 
'Oranges and lemons,'
ftell(fid)
ans = 20

Read the second line and examine the current position.

tline2 = fgetl(fid)  % read the second line 
tline2 = 
'Pineapples and tea.'
ftell(fid)
ans = 40

Read the thrid line and examine the current position.

tline3 = fgetl(fid)  % read the third line 
tline3 = 
'Orangutans and monkeys,'
ftell(fid)
ans = 64

To read line 2, set the position in the file to point to the beginning of line 2. Use fseek to set the position, and then perform a read operation.

fseek(fid,20,'bof');
fgetl(fid)
ans = 
'Pineapples and tea.'

Close the file.

fclose(fid); 

Input Arguments

collapse all

File identifier of an open file, specified as an integer. Before using fseek, you must use fopen to open the file and obtain its fileID.

Data Types: double

Number of bytes to move from origin, specified as an integer. The value of offset can be positive, negative, or zero.

Data Types: double

Starting location in the file, specified as a character vector, string scalar, or a scalar number.

'bof' or -1

Beginning of file

'cof' or 0

Current position in file

'eof' or 1

End of file

Data Types: double | char | string

Tips

  • If a file has n bytes of data, then those n bytes are in positions 0 through n-1.

Alternatives

To move to the beginning of a file, call

frewind(fileID)

This call is identical to

fseek(fileID, 0, 'bof')

Extended Capabilities

Introduced before R2006a

Was this topic helpful?