下面的问题与其说是问题,不如说是一种好奇。
我偶然发现了 this question ,提供了两个看似相同的不同答案。但他们不是,是什么让我思考。
想象一个 system
调用,它回显两行:
[~,message] = system( 'echo hello && echo world' );
返回:
hello
world
如果要将这些行写入.txt
文件并在记事本中打开它,常见的方法是:
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说:
To open files in text mode, attach the letter 't' to the permission argument, such as 'rt' or 'wt+'.
On Windows® systems, in text mode:
-Read operations that encounter a carriage return followed by a newline character ('\r\n') remove the carriage return from the input.-Write operations insert a carriage return before any newline character in the output.
所以根据我的理解,它基本上是这样的:
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/