How to get the final number of lines in a data file?
7 views (last 30 days)
Show older comments
Hi all, I have a data file as follow:
x 0 y 1
x 1.3 y 2.2
x 2.2 y 6
x 3.4 y 7.4
I need to read into this file, plot the data (which is done) and put the number of lines in the title of the plot. I uses the following code to get the number of lines:
count = 0;
while ~feof(fid)
count = count+1
end
however, as it is in a while-loop, the 'count' changes every time:
count =
1
count =
2
count =
3
count =
4
how to get a FINAL number of lines ? (aka, I want count = 4 and only =4, not varying during each time the loop running). as I need to put this 'final' number into title.
Thank you very much.
0 Comments
Accepted Answer
Walter Roberson
on 20 Aug 2015
count = 0;
while true
if ~ischar( fgetl(fid) ); break; end
count = count + 1;
end
fclose(fid)
title(sprintf('lines in file = %d', count));
Note that feof(fid) never predicts end of file. feof() is never true unless you have already tried to read after the end of file, so even with a completely empty file, feof() would not immediately be true.
You can tell you have reached end of file when fgetl() returns something that is not a character.
3 Comments
Walter Roberson
on 20 Aug 2015
fid = fopen ('data_chp11exe2.dat');
if fid == -1
disp('File open not successful')
else
x = [];
y = [];
count = 0;
while true
%following codes are to separate x and y values
% then use them to plot
aline = fgetl(fid);
if ~ischar(aline); break; end
aline = aline(3:length(aline));
[x_val, rest] = strtok(aline);
x_val = str2double(x_val);
[y_name, y_val] = strtok(rest);
y_val = strtrim(y_val);
y_val = str2double(y_val) ;
x = [x, x_val];
y = [y, y_val];
count = count+1;
end
fclose(fid);
area(x, y);
xlabel('x');
ylabel('y');
title(sprintf('number of lines:%d', count));
end
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!