Reading & Writing Text Files
Plain text files are the universal exchange format: log files, configuration files, reports, data exported by instruments. MATLAB handles them with a set of low-level functions inherited from C (fopen, fprintf, fgetl, fclose) plus a few convenient shortcuts such as fileread. This lesson covers the general tools; the next two focus on files full of numbers and on CSV files.
Note: every example here creates its own files in the folder it runs in, then reads them back.
Open, use, close
Working with a file is always three steps:
fid = fopen(name, mode)opens the file and returns a file identifier, a small integer that the other functions use to know which file you mean.- Read or write with
fidas the first argument. fclose(fid)closes the file. Until then, written data may still sit in a buffer, and the file stays locked on Windows.
| Mode | Meaning | If the file exists | If it doesn't |
|---|---|---|---|
'r' |
Read (the default) | Read from the start | Fails (fid = -1) |
'w' |
Write | Erased first | Created |
'a' |
Append | Writing adds to the end | Created |
'r+', 'w+', 'a+' |
Read and write | As r, w, a |
As r, w, a |
Adding t ('wt', 'rt') opens in text mode: on Windows, \n is then written as the Windows line ending \r\n and converted back when reading. On Linux and macOS it makes no difference.
Writing with fprintf
With a file identifier as the first argument, fprintf writes to the file instead of the screen, with the same format codes as usual (see Displaying Output):
fid = fopen('shopping.txt', 'w');
fprintf(fid, 'Shopping list\n');
fprintf(fid, '- %s\n', 'bread', 'apples', 'coffee'); % format reused for each argument
fclose(fid);
disp(fileread('shopping.txt'))Shopping list
- bread
- apples
- coffee
When there are more values than format codes, fprintf recycles the format, which is how the three items became three lines. With a matrix, it takes the values in column order, so transpose a matrix whose rows you want as lines:
data = [1 20.5 0.31; 2 21.0 0.29; 3 22.4 0.35]; % one row per measurement
fid = fopen('measurements.txt', 'w');
fprintf(fid, '%-4s %8s %6s\n', 'id', 'temp', 'err');
fprintf(fid, '%-4d %8.1f %6.2f\n', data'); % note the transpose
fclose(fid);
disp(fileread('measurements.txt'))id temp err
1 20.5 0.31
2 21.0 0.29
3 22.4 0.35
fileread(name) returns the whole file as one character vector, which is perfect for small files and quick checks like this one.
Checking that fopen worked
fopen doesn't stop with an error when it fails: it returns -1, and the second output explains why. Always check before using the identifier, otherwise the next call fails with a confusing "invalid file identifier" message:
[fid, msg] = fopen('no_such_file.txt', 'r');
if fid < 0
fprintf('Could not open the file: %s\n', msg);
else
fclose(fid);
endCould not open the file: No such file or directory
In functions, onCleanup guarantees the file is closed even if an error happens halfway through. The cleanup runs when the variable cleaner goes out of scope, which happens when the function returns or fails:
fid = fopen('letters.txt', 'w'); fprintf(fid, 'a\nb\nc\nd\n'); fclose(fid);
fprintf('%d lines\n', count_lines('letters.txt'));
try
count_lines('missing.txt');
catch err
disp(err.message)
end
function n = count_lines(name)
[fid, msg] = fopen(name, 'r');
if fid < 0
error('count_lines:open', 'Cannot open %s: %s', name, msg);
end
cleaner = onCleanup(@() fclose(fid)); % closes the file however we leave
n = 0;
while ischar(fgetl(fid))
n = n + 1;
end
end4 lines
Cannot open missing.txt: No such file or directory
Reading line by line: fgetl and fgets
fgetl(fid) reads the next line without its newline character; fgets(fid) keeps it. At the end of the file both return the number -1 instead of text, so the standard loop tests ischar:
fid = fopen('config.txt', 'w');
fprintf(fid, '# settings\nwidth = 800\n\nheight = 600\ntitle = Demo run\n');
fclose(fid);
fid = fopen('config.txt', 'r');
settings = struct();
while true
line = fgetl(fid);
if ~ischar(line), break; end % -1 means end of file
line = strtrim(line);
if isempty(line) || line(1) == '#' % skip blank lines and comments
continue
end
parts = strsplit(line, '=');
key = strtrim(parts{1});
value = strtrim(strjoin(parts(2:end), '='));
settings.(key) = value;
end
fclose(fid);
disp(settings)
fprintf('width + height = %d\n', str2double(settings.width) + str2double(settings.height)); width = 800
height = 600
title = Demo run
width + height = 1400
Values read from text are always text: str2double converts them to numbers (and returns NaN if the text isn't a number). The dynamic field name settings.(key) turns each key into a structure field.
The difference between fgetl and fgets is only the newline:
fid = fopen('two.txt', 'w'); fprintf(fid, 'first\nsecond\n'); fclose(fid);
fid = fopen('two.txt', 'r');
a = fgetl(fid);
b = fgets(fid);
c = fgetl(fid);
fclose(fid);
fprintf('fgetl: %d characters, fgets: %d characters (last one is char %d)\n', ...
numel(a), numel(b), double(b(end)));
fprintf('after the last line fgetl returns %d (class %s)\n', c, class(c));fgetl: 5 characters, fgets: 7 characters (last one is char 10)
after the last line fgetl returns -1 (class double)
Tip: you'll see
while ~feof(fid)loops in older code. They work, butfeofonly becomes true after a read hits the end, so the loop body must still handle a final-1. Theischartest above avoids that trap.
The whole file at once
For files that fit in memory, reading everything with fileread and then splitting is shorter and usually faster than a loop. Split on line breaks with regexp(..., 'split'); the pattern \r?\n accepts both Linux and Windows line endings:
fid = fopen('poem.txt', 'w');
fprintf(fid, 'Roses are red\nViolets are blue\n\nArrays start at one\n');
fclose(fid);
txt = fileread('poem.txt');
lines = regexp(txt, '\r?\n', 'split');
if isempty(lines{end}), lines(end) = []; end % the final newline leaves an empty piece
fprintf('%d lines, %d of them empty\n', numel(lines), sum(cellfun(@isempty, lines)));
for k = 1:numel(lines)
fprintf('%d: %s\n', k, lines{k});
end4 lines, 1 of them empty
1: Roses are red
2: Violets are blue
3:
4: Arrays start at one
strsplit(txt, newline) also works, but by default it merges consecutive delimiters and so silently drops blank lines; pass 'CollapseDelimiters', false to keep them.
Appending to a log file
Mode 'a' adds to the end of an existing file (or creates it), which is exactly what a log needs. Each run of this loop opens, writes one line and closes, so the file is complete even if the program crashes later:
if isfile('run.log'), delete('run.log'); end
for step = 1:3
fid = fopen('run.log', 'a');
fprintf(fid, 'step %d finished, residual %.1e\n', step, 10^(-2*step));
fclose(fid);
end
fprintf('%s', fileread('run.log'));step 1 finished, residual 1.0e-02
step 2 finished, residual 1.0e-04
step 3 finished, residual 1.0e-06
readlines and writelines (MATLAB)
MATLAB R2022a added one-call functions that return and accept string arrays (see String Arrays):
% MATLAB R2022a and later
writelines(["alpha", "beta", "", "gamma"], 'words.txt');
lines = readlines('words.txt', 'EmptyLineRule', 'skip')MATLAB output:
lines =
3×1 string array
"alpha"
"beta"
"gamma"Octave 11 has neither function. The portable equivalents are fprintf(fid, '%s\n', cellArray{:}) for writing and the fileread + regexp split shown above for reading:
words = {'alpha', 'beta', '', 'gamma'};
fid = fopen('words.txt', 'w');
fprintf(fid, '%s\n', words{:});
fclose(fid);
lines = regexp(fileread('words.txt'), '\n', 'split');
lines = lines(~cellfun(@isempty, lines)) % like 'EmptyLineRule', 'skip'lines =
{
[1,1] = alpha
[1,2] = beta
[1,3] = gamma
}
Text encodings
Files with accented letters or other non-ASCII characters are usually stored in UTF-8. Name the encoding as the fourth argument of fopen so it doesn't depend on the computer's settings: fopen(name, 'w', 'n', 'UTF-8') (the third argument, 'n', is the native byte order). One real difference to be aware of: MATLAB stores each character as one element, while Octave keeps text as UTF-8 bytes, so numel('café') is 4 in MATLAB but 5 in Octave. Code that only reads, splits and writes text works the same in both; code that counts characters of non-ASCII text does not.
Summary
fopen→ read/write →fclose; check forfid < 0and useonCleanupin functions.'w'erases,'a'appends,'r'reads;fprintf(fid, ...)writes formatted text and recycles the format over the data (transpose matrices).fgetl(no newline) /fgets(with newline) read line by line; stop when the result isn'tischar.fileread+regexp(txt, '\r?\n', 'split')reads a whole file into lines.readlines/writelinesare MATLAB-only shortcuts.
Next: Reading Numeric Data. Learn more: Python File Handling for comparison.
Test yourself
What happens to an existing file opened with fopen(name, 'w')?
- New text is added at the end
- Its contents are erased first
- fopen fails
- It is opened read-only
What does fgetl return when there are no more lines?
- An empty string
'' - The number -1
- NaN
- It throws an error
Why does fprintf(fid, '%d %d %d\n', M') use the transpose of M?
- fprintf can't read matrices
- fprintf consumes values in column order, so transposing makes each row of M one line
- To convert the values to text
- Transposing makes the file smaller