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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值