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

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:

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

关闭,则:

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

原文链接: https://www.cnblogs.com/submarinex/archive/2013/02/21/2920772.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/78596

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午6:35
下一篇 2023年2月9日 下午6:35

相关推荐