问题描述
我正在使用如下创建的基本std::ofstream
对象:
I'm working with a basic std::ofstream
object, created as follows:
output_stream = std::ofstream(output_file.c_str());
这将创建一个文件,并在其中放置一些信息.让我显示此类消息的示例:(监视"窗口摘录)
This creates a file, where some information is put in. Let me show an example of such a message: (Watch window excerpt)
full_Message "Error while processing message:\r\n\tForecast Request:"
这一切都可以,但是启动以下命令后,就会出现问题:
All this is ok, but after having launched following commands, there is a problem:
output_stream << full_Message;
output_stream.flush();
为了查看出什么问题,让我们看一下文件的十六进制转储:(这是文件的十六进制显示,如在Notepad ++中所示.为清楚起见,我拍摄了屏幕截图.)
In order to see what is wrong, let's look at the hexadecimal dump of the file: (this is a hexadecimal display of the file, as seen in Notepad++. For clarity reasons I've taken a screenshot.)
如您所见,字符0d
被加倍,从而显示以下内容:
As you can see, the character 0d
is doubled, resulting in following display:
Error while processing message:
Forecast Request:
(换行过多,两行应直接接在另一行之后)
(There's a newline too much, both lines should be directly one after the other)
在从UNIX/Linux到Windows的文件转换中,我知道添加了#13
字符,但这在这里无关紧要:我只是在Windows系统上处理Windows文件,因此应该无需添加任何#13
字符.
I am aware of the addition of #13
characters while doing file conversion from UNIX/Linux to Windows, but this is not relevant here: I'm purely working with a Windows file, on a Windows system, so there should be no need to add any #13
character.
有人知道如何避免增加这个额外的字符吗?
Does anybody have an idea how I can avoid this extra character being added?
预先感谢
推荐答案
流默认为文本模式,这意味着在Windows中,如果您编写\n
,则文件将获得\r\n
.因此,如果您编写\r\n
,则文件将获得\r\r\n
.
The streams default to text mode, which means that in Windows, if you write \n
then the file gets \r\n
. Therefore , if you write \r\n
then the file gets \r\r\n
.
要解决此问题,只需在代码中编写\n
即可;或以 binary模式打开文件:
To fix this, either just write \n
in your code; or open the file in binary mode:
auto output_stream = std::ofstream(output_file.c_str(), std::ios::binary);
这篇关于为什么std :: ofstream添加额外的#13(换行符)字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!