Export to Text Data Files with Low-Level I/O

Writing to Text Files

To create rectangular, delimited ASCII files (such as CSV files) from numeric arrays, use high-level functions such as dlmwrite. For more information, see Write to Delimited Data Files.

To create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes, use the low-level fprintf function. For more information, see the following sections.

    Note:   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.

Opening the File

As with any of the low-level I/O functions, before exporting, open or create a file with fopen, and obtain a file identifier. 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'.

When you finish processing the file, close it with fclose(fid).

Describing the Output

fprintf accepts arrays as inputs, and converts the numbers or characters in the arrays to text according to your specifications.

For example, to print floating-point numbers, specify '%f'. Other common conversion specifiers include '%d' for integers or '%s' for strings. For a complete list of conversion specifiers, see the fprintf reference page.

To move to a new line in the file, use '\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.

fprintf reapplies the conversion information to cycle through all values of the input arrays in column order.

For example, create a file named exptable.txt that contains a short table of the exponential function, and a text header:

% create a matrix y, with two rows
x = 0:0.1:1;
y = [x; exp(x)];

% open a file for writing
fid = fopen('exptable.txt', 'w');

% print a title, followed by a blank line
fprintf(fid, 'Exponential Function\n\n');

% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f  %f\n', y);

To view the file, use the type function:

type exptable.txt

This returns the contents of the file:

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:

fid = fopen('exptable_new.txt', 'w');

fprintf(fid, 'Exponential Function\n\n');
fprintf(fid, '%6.2f  %12.8f\n', y);


exptable_new.txt contains the following:

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

For more information, see Formatting Strings in the Programming Fundamentals documentation, and the fprintf reference page.

Appending or Overwriting Existing Files

By default, fopen opens files with read access. To change the type of file access, use the permission string in the call to fopen. Possible permission strings 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+'. For a complete list of permission values, see the fopen reference page.

    Note:   If you open a file for both reading and writing, you must call fseek or frewind between read and write operations.

Example — Append to an Existing Text File

Create a file changing.txt as follows:

myformat = '%5d %5d %5d %5d\n';

fid = fopen('changing.txt','w');
fprintf(fid, myformat, magic(4));

The current contents of changing.txt are:

   16     5     9     4
    2    11     7    14
    3    10     6    15
   13     8    12     1

Add the values [55 55 55 55] to the end of file:

% open the file with permission to append
fid = fopen('changing.txt','a');

% write values at end of file
fprintf(fid, myformat, [55 55 55 55]);

% close the file 

To view the file, call the type function:

type changing.txt

This command returns the new contents of the file:

   16     5     9     4
    2    11     7    14
    3    10     6    15
   13     8    12     1
   55    55    55    55

Example — Overwrite an Existing Text File

This example shows two ways to replace characters in a text file.

A text file consists of a contiguous string 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.

For example, replace the first line of changing.txt (created in the previous example) 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';

fid = fopen('changing.txt','r');
mydata = cell(1, numLines);
for k = 1:numLines
   mydata{k} = fgetl(fid);

mydata{replaceLine} = newText;

fid = fopen('changing.txt','w');
fprintf(fid, '%s\n', mydata{:});

The file now contains:

 This file originally contained a magic square
    2    11     7    14
    3    10     6    15
   13     8    12     1
   55    55    55    55

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. For example, replace the third line of changing.txt with [33 33 33 33]:

replaceLine = 3;
myformat = '%5d %5d %5d %5d\n';
newData = [33 33 33 33];

% move the file position marker to the correct line
fid = fopen('changing.txt','r+');
for k=1:(replaceLine-1);

% call fseek between read and write operations
fseek(fid, 0, 'cof');

fprintf(fid, myformat, newData);

The file now contains:

This file originally contained a magic square
    2    11     7    14
   33    33    33    33
   13     8    12     1
   55    55    55    55

Opening 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, fopen opens files for processing using the default encoding for your system. 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.

Was this topic helpful?