File Input and Output

Low-level file I/O pattern: fid = fopen(name, mode) ('r', 'w', 'a'), check fid ~= -1, read/write, then fclose(fid).

Concept

Numeric CSV / text matrix writematrix (R2019a+), csvwrite, dlmwrite

readmatrix, csvread, dlmread, load (plain numeric text) Tables (headers, mixed types)

readtable, detectImportOptions (MATLAB) Any formatted text fopen, fprintf, fclose

fopen, fgetl, fgets, fscanf, textscan, fclose, fileread save file.mat vars load file.mat (or S = load(...)) readmatrix/readtable (MATLAB) fread (with precision and byte order)

Low-level file I/O pattern: fid = fopen(name, mode) ('r', 'w', 'a'), check fid ~= -1, read/write, then fclose(fid). fgetl returns -1 (not text) at end of file.

File system helpers: exist(name, 'file'), dir, fullfile, fileparts, mkdir, delete, movefile, copyfile, pwd, cd.

Why It Matters

Test benches, data loggers and simulations produce files; MATLAB is often the tool that reads, cleans and summarizes them — and writes reports.

Syntax

fid = fopen('log.txt', 'w'); fprintf(fid, '%.3f,%d\n', [t; id]); fclose(fid);
C = textscan(fid, '%s %f', 'Delimiter', ',', 'HeaderLines', 1);
save('results.mat', 'data', 'cfg');   S = load('results.mat');
path = fullfile(folder, 'bench', 'log.csv');

Example

17.1 CSV, formatted text, textscan and MAT files

% --- write and read a CSV file with numeric data ---
data = [0 12.6 25; 1 12.5 26; 2 12.3 28];
csvwrite('bench_log.csv', data);                         % writematrix in newer MATLAB
back = csvread('bench_log.csv');                         % readmatrix in newer MATLAB
fprintf('CSV round trip equal: %d\n', isequal(back, data))

% --- formatted text with fopen/fprintf/fclose ---
fid = fopen('report.txt', 'w');
fprintf(fid, 'ECU,Firmware,Voltage\n');
ecus = {'VCU', 'BMS'}; fw = {'2.4.1', '1.9.0'}; volts = [12.6 11.9];
for k = 1:2
    fprintf(fid, '%s,%s,%.1f\n', ecus{k}, fw{k}, volts(k));
end
fclose(fid);

% --- read it back line by line ---
fid = fopen('report.txt', 'r');
header = fgetl(fid);
while true
    line = fgetl(fid);
    if ~ischar(line), break, end                          % fgetl returns -1 at end of file
    p = strsplit(line, ',');
    fprintf('%-4s firmware %s at %s V\n', p{1}, p{2}, p{3})
end
fclose(fid);

% --- textscan for mixed columns ---
fid = fopen('report.txt');
C = textscan(fid, '%s %s %f', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid);
fprintf('textscan: names %s, mean voltage %.2f\n', strjoin(C{1}', '/'), mean(C{3}))

% --- MAT files: save and load workspa
…

Expected Result

All four styles round-tripped their data. fgetl returned -1 at the end of the file, which the loop detected with ~ischar(line). Loading a MAT file into a variable (S = load(...)) keeps the loaded names inside a struct instead of polluting the workspace.

CSV round trip equal: 1
VCU  firmware 2.4.1 at 12.6 V
BMS  firmware 1.9.0 at 11.9 V
textscan: names VCU/BMS, mean voltage 12.25
loaded from MAT file: idle 750 rpm, fan on at 95 C, data 3x3
exist('report.txt') = 2 (2 = file)

Common Mistakes

Not closing files (fclose), especially after errors (use onCleanup).

Not checking fid == -1 after fopen (file missing, wrong folder).

Hard-coded paths with \ that break on Linux/macOS — use fullfile.

load without an output poisoning the workspace with unexpected variable names.

Best Practices

Prefer high-level functions (readmatrix, readtable) for standard formats; textscan for custom text.

Use S = load(...) and access S.name.

Store raw data unchanged; write processed results to new files.

Interview Relevance

Medium: "how do you read a CSV with headers?", "how do you read a file line by line?", "what is a MAT file?", "load vs S = load?".

Practice Questions

Write the numbers 1–10 and their squares to a CSV and read them back.

Count the lines of a text file with fgetl.

Save two variables to a MAT file, clear them, and load only one.

Read a JSON configuration with jsondecode(fileread('cfg.json')).

Quick Quiz

Q1. (Multiple choice) What does fgetl return at the end of a file? A) '' B) -1 C) NaN D) An error Answer: B.

Q2. (Predict the output) In the example, what was the mean voltage read with textscan?

Answer: 12.25 (verified).

Q3. (True/False) S = load('calib.mat') creates the variables directly in the workspace.

Answer: False. They become fields of S.

Q4. (Find the bug) fid = fopen('data.txt'); line = fgetl(fid); fails with "Invalid file identifier".

Answer: The file wasn't found (fid is −1); check the current folder or use a full path, and test fid before reading.

Coding Challenge

Write three bench readings (time, voltage) to readings.txt with a header, read them back with textscan, print the maximum voltage and delete the file.

t = [0 1 2]; v = [12.6 12.9 12.4];
fid = fopen('readings.txt', 'w');
fprintf(fid, 'time,voltage\n');
fprintf(fid, '%d,%.1f\n', [t; v]);
fclose(fid);
fid = fopen('readings.txt');
C = textscan(fid, '%f %f', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid);
[vmax, i] = max(C{2});
fprintf('max voltage %.1f V at t = %d s\n', vmax, C{1}(i))
delete('readings.txt');