Opening the book…
Sometimes we do not want to read the entire file all at once. Instead, we may want to read one line, process that line, then move to the next line. The function fgetl is useful for this.
fgetl reads the next line of a file and removes the newline character at the end of the line. The format is:
aline = fgetl(fid)
If there is another line to read, fgetl returns that line as a character vector. If MATLAB has reached the end of the file, fgetl returns -1.
Basic fgetl Pattern
fid = fopen('example.txt');
if fid == -1
disp('File open was not successful')
else
while true
aline = fgetl(fid);
if aline == -1
break
end
disp(aline)
end
fclose(fid);
end
The phrase while true creates a loop that keeps going until we explicitly stop it with break. In this case, the loop stops when fgetl returns -1, which means there are no more lines to read.
Example 9.4: Formatting Phone Numbers
Formatting Phone Numbers
Suppose we have a file named phones.dat containing phone numbers in this form:
6012425932 6178987654 8034562468 9492150918
We want MATLAB to display the phone numbers with hyphens, like this:
601-242-5932
The following script reads the file one line at a time, checks that each number has 10 digits, and then prints the formatted phone number.
fid = fopen('phones.dat');
if fid == -1
disp('File open was not successful')
else
while true
phone = fgetl(fid);
if phone == -1
break
end
if length(phone) == 10 && all(isstrprop(phone, 'digit'))
fprintf('%s-%s-%s\n', phone(1:3), phone(4:6), phone(7:10));
else
fprintf('Invalid phone number: %s\n', phone);
end
end
fclose(fid);
end
This is a good example of why line-by-line reading can be useful. We can check and process each line individually.
This page titled 9.7: Reading One Line at a Time with fgetl was last modified on Tue, 30 Jun 2026 02:12:02 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.
The book could not be loaded just now.