Move to specified position in file
Move to New Position in File
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.
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,'
ans = 20
Read the second line and examine the current position.
tline2 = fgetl(fid) % read the second line
tline2 = 'Pineapples and tea.'
ans = 40
Read the third line and examine the current position.
tline3 = fgetl(fid) % read the third line
tline3 = 'Orangutans and monkeys,'
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.
ans = 'Pineapples and tea.'
Close the file.
fileID — File identifier
File identifier of an open file, specified as an integer. Before using
fseek, you must use
fopen to open the file and
offset — Number of bytes
Number of bytes to move from
origin, specified as an
integer. The value of
offset can be positive, negative,
origin — Starting location
integer | character vector | string
Starting location in the file, specified as a character vector, string scalar, or a scalar number.
Beginning of file
Current position in file
End of file
If a file has
nbytes of data, then those
nbytes are in positions
To move to the beginning of a file, call
This call is identical to
fseek(fileID, 0, 'bof')
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
When the MATLAB® behavior differs from the C compiler behavior, the generated code matches the C compiler behavior. Examples include:
Seeking past the end of a file.
Seeking away from the end of a file opened with append access.
The offset is passed to the C run-time environment as a signed long data type. Therefore, the offset value must fit in the long data type on the target hardware.
Run code in the background using MATLAB®
backgroundPool or accelerate code with Parallel Computing Toolbox™
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version HistoryIntroduced before R2006a
R2022b: Use function in thread-based environments
This function supports thread-based environments.