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

来源:互联网 发布:游戏存档软件 编辑:程序博客网 时间:2024/06/05 00:38
Write to Text Files Using fprintf

Open Script

This example shows how to create text files, including combinations of numeric and character data and nonrectangular files, using the low-levelfprintf function.

fprintf is based on its namesake in the ANSI® Standard C Library. However, MATLAB® uses a vectorized version offprintf 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 Function0.000000 1.0000000.100000 1.1051710.200000 1.2214030.300000 1.3498590.400000 1.4918250.500000 1.6487210.600000 1.8221190.700000 2.0137530.800000 2.2255410.900000 2.4596031.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

Open Script

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 tofopen. 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 callfseek 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    1513     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);endfclose(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, fopen opens files for processing using the default encoding for your system. To determine the default, open a file, and callfopen 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 thefopen reference page.

0 0