c++ - 是否建议始终使用 'binary' 模式打开文件?

标签 c++ c++11 ofstream

我有一个通用函数:

bool WriteFile(const string& strFileContent, const wpath& pathFile)

在这个函数中我有下面一行:

std::ofstream outStream(pathFile.string().c_str(), std::ios::out);

由于这个函数是通用的,所以我有时会用它来编写二进制文件。我注意到使用 openmode std::ios::out不是二进制数据的正确文件,写入的文件也不像我预期的那样,意思是,文件不等于 strFileContent 中定义的实际数据。 .

所以我做了这个简单的修复:

std::ofstream outStream(pathFile.string().c_str(), std::ios::out | std::ios::binary);

这解决了二进制文件的问题,并且对文本文件 也非常有效。

问题

如果打开模式std::ios::out | std::ios::binary适用于二进制和文本数据,其中之一不是多余的吗?
如果是这样,我是否应该始终使用 std::ios::out | std::ios::binary ?
如果不是,在这种情况下使用 std::ios::out | std::ios::binary不推荐?

最佳答案

我已经阅读了一些相关帖子,但找不到太多新内容。
除了换行转换,我找不到其他更喜欢文本模式的理由。
顺便说一句,在 GNU C 库和所有 POSIX 系统上,文本流和二进制流之间没有区别。

参见 here了解 GCC 文档中对此的解释。

我真的很想找到一些关于强调文本的例子。

Since a binary stream is always more capable and more predictable than a text stream, you might wonder what purpose text streams serve. Why not simply always use binary streams? The answer is that on these operating systems, text and binary streams use different file formats, and the only way to read or write “an ordinary file of text” that can work with other text-oriented programs is through a text stream.

关于c++ - 是否建议始终使用 'binary' 模式打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30973471/

相关文章:

c++ - "Garbled"在 VST 插件中使用 FFTW 的声音

c++ - 每当需要 ostream 时使用 ofstream

c++ - 函数不能正确计算文件中的整数?

C++11 operator""with double parameter

c++ - std::ofstream 无缘无故地重复和丢失写入的数据

c++ - 修改哈希函数

c++ - C++ 中二元谓词的求值

c++,通过删除[] x [i]缩小动态数组

通过引用传递的 C++0x 初始化列表

c# - C++ 等同于 C# 的 Func<T, TResult>