以下问题与其说是一个问题,不如说是一个好奇心。
我偶然发现了 this question ,提供了两个不同的答案,它们似乎是等效的。但他们不是,是什么让我想到。
想象一个 system
调用,它回显了两行:
[~,message] = system( 'echo hello && echo world' );
返回:
hello
world
如果想将这些行写入
.txt
-file 并在记事本中打开它,常用的方法是:fid = fopen([pwd '\helloworld.txt'],'w');
fprintf(fid, '%s\n', message);
fclose(fid);
winopen('helloworld.txt')
返回
hello world
由于记事本显然无法正确识别换行符
\n
,解决方案是使用 'wt'
而不是 'w'
来强制执行文本模式,这应该很慢。返回:hello
world
documentation to fopen permissions 说:
所以在我看来,它基本上是:
fprintf(fid, '%s\r\n', message)
但输出再次是:
hello world
'wt'
还有什么?如何使用 'w'
获得相同的行为?如果这个问题毫无意义且微不足道,我很抱歉,但是在令人沮丧的几个小时之后,我只是好奇我错过了什么。
最佳答案
在我的理解中确实如此
fprintf(fid, '%s', strrep(message, sprintf('\n'), sprintf('\r\n'))
如果你这样做
fprintf(fid, '%s\r\n', message)
您只在消息的最后添加一个回车和一个换行符,即“world\n”之后。“hello”和“world”之间的换行符仍然没有回车。
所以在你的 fprintf 你的消息是
"hello\nworld\n\r\n"
,它应该是 "hello\r\nworld\r\n"
您可以通过以字节为单位读取输出文件来检查这一点,知道
\n
将是 10
为 uint8
和 \r
为 13
:>> fid = fopen('test.txt','wt');
>> fprintf(fid, 'hello\nworld\n');
>> fclose(fid);
>> fid = fopen('test.txt','r');
>> bytes = fread(fid, Inf, 'uint8')'
bytes =
104 101 108 108 111 13 10 119 111 114 108 100 13 10
关于matlab - 与正常模式下正确设置的回车相比,为什么 fprintf 在文本模式下的行为不同?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19298269/