how to count the number of lines of an external txt file
조회 수: 90 (최근 30일)
이전 댓글 표시
답변 (2개)
Davide Masiello
2022년 5월 2일
Not sure if there is a better way, but this will work
fid = fopen('a.txt','r');
n = 0;
while ~feof(fid)
fgetl(fid);
n = n+1;
end
fclose(fid);
n
댓글 수: 1
Rik
2022년 5월 2일
Your code doesn't skip empty lines in the middle of the file
% Write an example file with a blank line
fid=fopen('a.txt','w');
fprintf(fid,'line1\n\nline3\n');
fclose(fid);
% Run your code
fid = fopen('a.txt','r');
n = 0;
while ~feof(fid)
fgetl(fid);
n = n+1;
end
fclose(fid);
n
Rik
2022년 5월 2일
The problem with your question is that it lacks a definition of line. If your file ends with char(10) or char(13) does that signify a new line (meaning you have a trailing empty line)?
txt=readfile('https://www.mathworks.com/matlabcentral/answers/uploaded_files/985140/a.txt',...
'EmptyLineRule','skip')
a=numel(txt)
This is the choice that my readfile function makes. If you use R2020b or later you will be able to use the builtin readlines function. For older releases (or GNU Octave) you will need to use readfile.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!