Read file from line #1 to line #2

Hi,
I'd like to know hot to read a text file between certain line numbers. It's a huge file and I only need to use a portion of it.
Thanks in advance,
Ed

 Accepted Answer

Walter Roberson
Walter Roberson on 29 Aug 2011
You cannot tell fgetl() which line to start reading from.
If you have read past a section of file and want to go back, then you need to use fseek(). Note though that fseek() cannot seek by line number. You may need to fseek() to the beginning of the file and then use a loop to read and discard a line at a time.
When you are reading in the file the first time, if you can detect (e.g., with a counter) that you are at a place you are going to want to come back to later, you can use ftell() to record the location in a way that fseek() knows how to use to go back to that exact spot.

2 Comments

Walter,
Thank you. It worked quite nicely. I scanned my file to determine where I wanted to start reding, then called ftell()at that line, and used that in fseek() to go straight to the spot I wanted to start reading.
Cheers,
Ed
How do you scan the file? Does your file contain only one line?

Sign in to comment.

More Answers (1)

fgetl() will read one line at a time. If you know which lines to read, you can write a for-loop to skip the previous lines.
Assume you want to read from line StartLine=100, for example
fid=fopen('test.txt','rt');
StartLine=100;
for k=1:StartLine-1
fgetl(fid); % read and dump
end
Fline=fgetl(fid); % this is the 100th line
%do stuff
fclose(fid)

1 Comment

I do know which lines I wanna read. However, how can I tell "fgetl()" which line to start reading? I first scan the whole file using
tline = fgetl(fr1);
By the time it has scanned it, tline = -1. I know need to reset fget to go and continue reading from a certain line number all the way down the end of the file.
Thanks,
Ed

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!