Difference in using read/write when stream is opened with/without ios::binary mode(使用/不使用 ios::binary 模式打开流时使用读/写的区别)
问题描述
在我使用以下代码片段的实验中,我没有发现任何特别的区别,无论是使用还是不使用 ios:binary 模式创建流:
In my experiments with the following code snippet, I did not find any particular difference whether i created the streams with/without the ios:binary mode:
int main()
{
    ifstream ostr("Main.cpp", ios::in | ios::binary | ios::ate);
    if (ostr.is_open())
    {
        int size = ostr.tellg();
        char * memBlock = new char[size + 1];
        ostr.seekg(0, ios::beg);
        ostr.read(memBlock, size);
        memBlock[size] = ' ';
        ofstream file("trip.cpp", ios::out | ios::binary);
        file.write(memBlock, size);
        ostr.close();
    }
}
在这里,我试图将原始源文件复制到另一个具有不同名称的文件中.
Here I am trying to copy the original source file into another file with a different name.
我的问题是在使用/不使用 ios::binary 模式打开 fstream 对象时,读/写调用(与二进制文件 IO 相关联)有什么区别?使用二进制模式有什么好处吗?文件IO什么时候用什么时候不用?
My question is what is the difference between the read/write calls(which are associated with binary file IO) when an fstream object is opened with/without ios::binary mode ? Is there any advantage of using the binary mode ? when to and when not to use it when doing file IO ?
推荐答案
binary 和 text 模式之间的唯一区别是如何处理 '
' 字符.
The only difference between binary and text mode is how the '
' character is treated.
在binary 模式下,没有 翻译.
在text模式下
在写入时被翻译成行尾.
在 text 模式下,end of line sequence 在读取时被翻译成 
.
In text mode 
 is translated on write into a the end of line sequence.
In text mode end of line sequence is translated on read into 
.
行尾是平台相关的.
示例:
LF    (' x0A'):      Multics, Mac OS X, BeOS, Amiga, RISC OS
CRLF  (' x0D x0A'): Microsoft Windows, DEC TOPS-10, RT-11
CR:   (' x0D'):      TRS-80, Mac OS Pre X
RS:   (' x1E'):      QNX pre-POSIX implementation.
                        这篇关于使用/不使用 ios::binary 模式打开流时使用读/写的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用/不使用 ios::binary 模式打开流时使用读/写的区别
				
        
 
            
        - 从python回调到c++的选项 2022-11-16
 - 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
 - STL 中有 dereference_iterator 吗? 2022-01-01
 - 使用/clr 时出现 LNK2022 错误 2022-01-01
 - 近似搜索的工作原理 2021-01-01
 - Stroustrup 的 Simple_window.h 2022-01-01
 - C++ 协变模板 2021-01-01
 - 如何对自定义类的向量使用std::find()? 2022-11-07
 - 静态初始化顺序失败 2022-01-01
 - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
 
						
						
						
						
						
				
				
				
				