Read an input file- process it line by line
Ältere Kommentare anzeigen
Hi I'm trying to figure out how to process an input file, where you check to see if each line is a word. But I don't have any clue on how to begin doing so. I would use something like "load" I think? Then I would save that word in a variable.
Akzeptierte Antwort
Weitere Antworten (1)
Raymond Chiu
am 9 Mai 2018
See: https://www.mathworks.com/help/matlab/ref/feof.html
fid = fopen('badpoem.txt');
while ~feof(fid)
tline = fgetl(fid);
disp(tline)
end
fclose(fid);
2 Kommentare
qilin guo
am 7 Jul. 2020
Great!
Walter Roberson
am 7 Jul. 2020
Caution: feof() does not reliably predict end-of-file.
The underlying C and POSIX libraries are explicit that feof is not set until an attempt is made to read past end of file and the attempt fails -- you have to try to pick up the next envelope before you find out that there is no next envelope.
MATLAB documents that at least under some conditions, feof() will be set if there is no further input, even if you have not tried to read the input.
With regards to using fgets() or fgetl(), if the file happens to end in a newline character, then the fgets() or fgetl() logically ends there, before you have looked to see if there are any more characters. If MATLAB can tell you feof() at that point, then it could only do so by "peeking ahead", which is not strictly forbidden but can lead to subtle confusion about the state and would not be recommended by POSIX.
With regards to using fgets() or fgetl(), if the file does not happen to end in a newline character (which is entirely valid), then fgets() or fgetl() would not know they had finished reading until they got told end-of-file by the I/O system, and it is normal and expected the feof() would become true in that case.
When you using fread(), or when you use I/O on a serial port or on a number of other kinds of device, or on memory-mapped files, it is a violation of POSIX for feof() to "predict" end of file before it has been specifically signalled (devices) or before an attempt has been made to read past end of file (fread). I think I have encountered cases where MATLAB is violating that POSIX policy, but I am not certain of that.
TLDR: after using fgets() or fgetl() you should always check that what you got back was not the end of file indicator, instead of relying on feof() already being true if there is no more to read:
fid = fopen('badpoem.txt');
while true
tline = fgetl(fid);
if ~ischar(tline); break; end %end of file
disp(tline);
end
Note: in the case of a line that has no characters other than the end-of-line markers, then the result of fgetl() will be the empty character array, ''
Kategorien
Mehr zu Scripts finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!