Documentation

fseek

移至文件中的指定位置

Syntax

fseek(fileID, offset, origin)
状态= fseek(___)

Description

example

fseek(fileID,offset,或者igin)sets the file position indicatoroffsetbytes from或者iginin the specified file.

状态= fseek(___)returns0when the operation is successful. Otherwise,fseekreturns-1。使用任何以前的输入参数组合。

Examples

collapse all

Open the followingbadpoem.txtfile and perform read operations (which advance the position pointer) and then useseekto move to a new position in the file.

Usefopento open the file. Then, useftellto 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. Usefgetlto read andfseekto 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)%阅读第二行
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 ='猩猩和猴子,'
ftell (fid)
ans = 64

To read line 2, set the position in the file to point to the beginning of line 2. Usefseekto 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

文件标识符of an open file, specified as an integer. Before usingfseek, you must usefopen打开文件并获得其fileID

Data Types:double

Number of bytes to move from或者igin, specified as an integer. The value ofoffsetcan 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'或者-1

Beginning of file

'cof'或者0

Current position in file

'eof'或者1

End of file

Data Types:double|char|string

Tips

  • If a file hasnbytes of data, then thosenbytes are in positions0throughn-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?