How to get the final number of lines in a data file?

조회 수: 3 (최근 30일)
smo
smo 2015년 8월 20일
댓글: smo 2015년 8월 20일
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.

채택된 답변

Walter Roberson
Walter Roberson 2015년 8월 20일
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
Walter Roberson
Walter Roberson 2015년 8월 20일
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
smo
smo 2015년 8월 20일
Thank you so much.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by