Difference between fprintf(fid, [str, 13 10]) and fprintf(fid, [str, '\n']) ?
1 次查看(过去 30 天)
显示 更早的评论
Hello all,
Today I was constructing datafiles using the fprintf(fid, [str, '\n']) synthaxe (str contains some num2str-ed numerical values)
However the datafiles produced this way weren't properly recognized by the data-reduction software I am supposed to use with those datafiles.
Instead, I tried fprintf(fid, [str, 13 10]) to construct my datafiles...and the data-reduction software was perfectly OK with the datafiles written this way !
Do you know what is the reason of this difference between '\n' and [13 10] output?
Just curiosity
Thanks in advance !
PS: Of course the first thing to say is that my data-reduction software is not so good at importing datafiles...
2 个评论
Stephen23
2020-11-18
编辑:Stephen23
2020-11-20
Note that although it is possible to concatenate your data string onto '\n' to generate the format string this can have unintended side-effects if the strings being concatenated contain special characters (i.e. ones which need to be escaped). So the more robust and efficient approach is to provide the data string as an input to fprintf:
fprintf(fid,'%s\n',str)
Note that while you can specify the carriage return and linefeed characters by specifying them both explicitly in the format string (as Ameer Hamza's answer shows), the recommended platform independent approach is to open the file in text mode, which on Windows automatically does this conversion for you:
fid = fopen(..,'wt'); % open in text mode...
fprintf(fid,'%s\n',str) % \r is added automatically!
fclose(fid);
Using text mode means you can write the same code for any OS and not worry about what newlines it uses.
采纳的回答
Ameer Hamza
2020-11-18
编辑:Ameer Hamza
2020-11-18
ASCII 13 is carriage return character. It can be combined with newline (ASCII 10) to move to beginning of next line. Following line will also work
fprintf(fid, [str, '\r\n'])
It is not unreasonable to use both of them together, and your software is following this convention. Read here: https://en.wikipedia.org/wiki/Carriage_return
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!