MATLAB Answers


open file, read a line then, rewind a line

Asked by Sam
on 30 Nov 2012

after fgetl(fid), the file position indicatior will be moved to the next line in the file, how could I rewind the indicator back 1 line in the file so when I call fgetl(fid) the second time it would return the same line?


What is your goal?

on 30 Nov 2012

say this is the text file i want to read

    my line 1
    my line 2
    my line 3
    my line 4

say after some steps, fgetl(fid) would return 'my line 3', then what should I do so when I call fgetl(fid) after this, it would still return 'my line 3'?


No products are associated with this question.

1 Answer

Answer by Matt J
on 30 Nov 2012
Edited by Matt J
on 30 Nov 2012

Use FTELL to measure the position in bytes of each line. Then use FREWIND and/or FSEEK to go to the desired position.

  1 Comment

Technical note:

If a file is opened with 'rt', which should be used for text files, then the value returned by ftell() is an arbitrary "token" rather than a file offset in bytes. Using the same token will get you to the same position, but you cannot do computations on the tokens.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!