Export to Text Data Files with Low-Level I/O
Write to Text Files Using fprintf
This example shows how to create text files, including combinations of numeric and character data and nonrectangular files, using the low-level fprintf
function.
fprintf
is based on its namesake in the ANSI® Standard C Library. However, MATLAB® uses a vectorized version of fprintf
that writes data from an array with minimal control loops.
Open the File
Create a sample matrix y
with two rows.
x = 0:0.1:1; y = [x; exp(x)];
Open a file for writing with fopen
and obtain a file identifier, fileID
. By default, fopen
opens a file for read-only access, so you must specify the permission to write or append, such as 'w'
or 'a'
.
fileID = fopen('exptable.txt','w');
Write to the File
Write a title, followed by a blank line using the fprintf
function. To move to a new line in the file, use '\n'
.
fprintf(fileID, 'Exponential Function\n\n');
Note: Some Windows® text editors, including Microsoft® Notepad, require a newline character sequence of '\r\n'
instead of '\n'
. However, '\n'
is sufficient for Microsoft Word or WordPad.
Write the values in y
in column order so that two values appear in each row of the file. fprintf
converts the numbers or characters in the array inputs to text according to your specifications. Specify '%f'
to print floating-point numbers.
fprintf(fileID,'%f %f\n',y);
Other common conversion specifiers include '%d'
for integers or '%s'
for characters. fprintf
reapplies the conversion information to cycle through all values of the input arrays in column order.
Close the file using fclose
when you finish writing.
fclose(fileID);
View the contents of the file using the type
function.
type exptable.txt
Exponential Function 0.000000 1.000000 0.100000 1.105171 0.200000 1.221403 0.300000 1.349859 0.400000 1.491825 0.500000 1.648721 0.600000 1.822119 0.700000 2.013753 0.800000 2.225541 0.900000 2.459603 1.000000 2.718282
Additional Formatting Options
Optionally, include additional information in the call to fprintf
to describe field width, precision, or the order of the output values. For example, specify the field width and number of digits to the right of the decimal point in the exponential table.
fileID = fopen('exptable_new.txt', 'w'); fprintf(fileID,'Exponential Function\n\n'); fprintf(fileID,'%6.2f %12.8f\n', y); fclose(fileID);
View the contents of the file.
type exptable_new.txt
Exponential Function 0.00 1.00000000 0.10 1.10517092 0.20 1.22140276 0.30 1.34985881 0.40 1.49182470 0.50 1.64872127 0.60 1.82211880 0.70 2.01375271 0.80 2.22554093 0.90 2.45960311 1.00 2.71828183
Append to or Overwrite Existing Text Files
This example shows how to append values to an existing text file, rewrite the entire file, and overwrite only a portion of the file.
By default, fopen
opens files with read access. To change the type of file access, use the permission specifier in the call to fopen
. Possible permission specifiers include:
'r'
for reading'w'
for writing, discarding any existing contents of the file'a'
for appending to the end of an existing file
To open a file for both reading and writing or appending, attach a plus sign to the permission, such as 'w+'
or 'a+'
. If you open a file for both reading and writing, you must call fseek
or frewind
between read and write operations.
Append to Existing Text File
Create a file named changing.txt
.
fileID = fopen('changing.txt','w'); fmt = '%5d %5d %5d %5d\n'; fprintf(fileID,fmt, magic(4)); fclose(fileID);
The current contents of changing.txt
are:
16 5 9 4
2 11 7 14
3 10 6 15
13 8 12 1
Open the file with permission to append.
fileID = fopen('changing.txt','a');
Write the values [55 55 55 55]
at the end of file:
fprintf(fileID,fmt,[55 55 55 55]);
Close the file.
fclose(fileID);
View the contents of the file using the type
function.
type changing.txt
16 5 9 4 2 11 7 14 3 10 6 15 13 8 12 1 55 55 55 55
Overwrite Entire Text File
A text file consists of a contiguous set of characters, including newline characters. To replace a line of the file with a different number of characters, you must rewrite the line that you want to change and all subsequent lines in the file.
Replace the first line of changing.txt
with longer, descriptive text. Because the change applies to the first line, rewrite the entire file.
replaceLine = 1; numLines = 5; newText = 'This file originally contained a magic square'; fileID = fopen('changing.txt','r'); mydata = cell(1, numLines); for k = 1:numLines mydata{k} = fgetl(fileID); end fclose(fileID); mydata{replaceLine} = newText; fileID = fopen('changing.txt','w'); fprintf(fileID,'%s\n',mydata{:}); fclose(fileID);
View the contents of the file.
type changing.txt
This file originally contained a magic square 2 11 7 14 3 10 6 15 13 8 12 1 55 55 55 55
Overwrite Portion of Text File
Replace the third line of changing.txt with [33 33 33 33]
. If you want to replace a portion of a text file with exactly the same number of characters, you do not need to rewrite any other lines in the file.
replaceLine = 3;
myformat = '%5d %5d %5d %5d\n';
newData = [33 33 33 33];
Move the file position marker to the correct line.
fileID = fopen('changing.txt','r+'); for k=1:(replaceLine-1); fgetl(fileID); end
Call fseek
between read and write operations.
fseek(fileID,0,'cof');
fprintf(fileID, myformat, newData);
fclose(fileID);
View the contents of the file.
type changing.txt
This file originally contained a magic square 2 11 7 14 33 33 33 33 13 8 12 1 55 55 55 55
Open Files with Different Character Encodings
Encoding schemes support the characters required for particular alphabets, such as those for Japanese or European languages. Common encoding schemes include US-ASCII or UTF-8.
If you do not specify an encoding scheme when opening a file for reading,
fopen
uses auto character-set detection to determine the encoding. If
you do not specify an encoding scheme when opening a file for writing,
fopen
defaults to using UTF-8 in order to provide interoperability
between all platforms and locales without data loss or corruption.
To determine the default, open a file, and call fopen
again with the
syntax:
[filename, permission, machineformat, encoding] = fopen(fid);
If you specify an encoding scheme when you open a file, the
following functions apply that scheme: fscanf
, fprintf
, fgetl
, fgets
, fread
,
and fwrite
.
For a complete list of supported encoding schemes, and the syntax
for specifying the encoding, see the fopen
reference
page.