Why does FPRINTF put strange characters in files when using MATLAB for the PC under Windows or DOS?

9 views (last 30 days)
A file created using FPRINTF with MATLAB for the PC may not be readable by the Notepad editor. Notepad views the file as one long line.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 9 Sep 2009
The contents of the file are shown in a single line because Notepad cannot interpret the UNIX single new line character as being an actual Windows new line character.
The default "NewLine" indicator in UNIX is the line feed character (LF, \n), whereas the default "NewLine" indicator in DOS is a carriage return (CR, \r) followed by a line feed (CR/LF, \r\n).
As a workaround, open the file in text mode instead of binary mode. This can be done using the 't' flag, in addition to the flag which specifies the method for opening the file (i.e. ' r' for Read, 'w' for Write, etc.), for example:
a=floor(10*rand(1,20));
fid=fopen('test.dat','wt');
fprintf(fid,'%2.5f\n',a);
fclose(fid);
Using 'wt' rather than 'w' tells MATLAB to write in text mode rather than binary mode.
Alternatively, you may be able to view the file normally using Wordpad.
When writing data to a text file, you always need to specify a new line character. The difference between using FOPEN with the option 'w' and the option 'wt' for write operations is explained in the documentation:
"[...]. On a write or append operation, MATLAB inserts a carriage return before any newline character."
This means that you have two options when writing text files for Windows:
1. Open the file with the option 'wt' and only use '\n' as the new line character:
fid = fopen('test.txt', 'wt+')
for i=1:3
fprintf(fid, 'Hello\n');
end
fclose(fid)
2. Open the file with the option 'w' and use '\r\n' as the new line character:
fid = fopen('test.txt', 'w+')
for i=1:3
fprintf(fid, 'World\r\n');
end
fclose(fid)
As a reference:
\r = Carriage Return (CR) = ASCII Code 13 (HEX: 0D)
\n = Line Feed (LF) = New Line = ASCII Code 10 (HEX: 0A)

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!