读写文本文件和二进制文件——二进制模式

fstream::binary

开启:新行采用‘LF’,作为一个字节;

关闭:新行采用‘CR’‘LF’组合,作为一个字节。

关于‘CR’‘LF’,参见:http://en.wikipedia.org/wiki/Newline

以下是《C++ Primer》第四版中的一段代码:

 1 int main()
 2 {
 3     fstream fInOut("copyOut", fstream::ate | fstream::in | fstream::out | fstream::binary);      
 4     if (!fInOut)
 5     {
 6         cerr << "Unable to open file!" << endl;
 7         return EXIT_FAILURE;
 8     }
 9 
10     ifstream::pos_type ptEndMark = fInOut.tellg();
11     fInOut.seekg(0, fstream::beg);
12     int nCnt = 0;
13     string strLine;
14     while (fInOut && fInOut.tellg() != ptEndMark && getline(fInOut, strLine))
15     {
16         nCnt += strLine.size() + 1;
17         ifstream::pos_type ptMark = fInOut.tellg();
18         fInOut.seekp(0, fstream::end);
19         fInOut << nCnt;
20         if (ptMark != ptEndMark)
21             fInOut << " ";
22         fInOut.seekg(ptMark);
23     }
24     fInOut.clear();
25     fInOut.seekp(0, fstream::end);
26     fInOut << "\n";
27 
28     return 0;
29 }

对于文件 “copyOut”

开启 fstream::binary:

关闭,则:


/**************************************************************************
                  原文来自博客园——Submarinex的博客: www.cnblogs.com/submarinex/               
  *************************************************************************/

原文地址:https://www.cnblogs.com/submarinex/p/2920772.html