フィルターのクリア

How to do a loop in a text file until an empty line is found

26 ビュー (過去 30 日間)
Hugo
Hugo 2020 年 11 月 3 日
回答済み: Image Analyst 2020 年 11 月 4 日
Hello,
I would like to open an external text file and do a loop that scans all the lines of the text file until an empty line is found. I know how to code what I would like to do, but I am not sure how I can replace my "For" cycle by a "While" cycle. Could someone help?
I thank you in advance,
Best regards,
Hugo

採用された回答

Cris LaPierre
Cris LaPierre 2020 年 11 月 3 日
編集済み: Cris LaPierre 2020 年 11 月 3 日
Look at the example on the documentation page for fgetl. Assuming you are doing this in a loop (for or while, doesn't matter), you can use the break command to stop if the result of fgetl is empty.

その他の回答 (1 件)

Image Analyst
Image Analyst 2020 年 11 月 4 日
Try this:
% Open the file for reading in text mode.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
lineCounter = 1;
while ischar(textLine)
% Print out what line we're operating on.
fprintf('%s\n', textLine);
% Read the next line.
textLine = fgetl(fileID);
if length(textLine) == 0
break;
end
lineCounter = lineCounter + 1;
end
% All done reading all lines, so close the file.
fclose(fileID);
You might also want to look at strtrim() to handle lines that have nothing but spaces on them. Not sure if you want to break on a line that was a space or not.

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by