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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by