Difference between fprintf(fid, [str, 13 10]) and fprintf(fid, [str, '\n']) ?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Julien Leger
el 18 de Nov. de 2020
Comentada: Julien Leger
el 20 de Nov. de 2020
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 comentarios
Stephen23
el 18 de Nov. de 2020
Editada: Stephen23
el 20 de Nov. de 2020
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.
Respuesta aceptada
Ameer Hamza
el 18 de Nov. de 2020
Editada: Ameer Hamza
el 18 de Nov. de 2020
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!