现在的位置: 首页 > 综合 > 正文

C/C++输出流写文件的一点误区

2013年08月02日 ⁄ 综合 ⁄ 共 455字 ⁄ 字号 评论关闭

先看下面的代码:

#include <fstream>
#include <windows.h>
using namespace std;

int main(int argc, char* argv[])
{
 ofstream of;
 of.open("d://temp");//文件temp
WORD a = 0x1234;

 of.write((char*) &a, sizeof(WORD));
 of.close();
}
 最后写入文件的结果是:34 12

如果把WORD a = 0x1234;改为WORD a = 0x0a34;

输出的结果是:34 0d 0a

为什么不是34  0a 而是34 0d 0a

因为of.open("d://temp");是默认按字节流来打开文件,而微软操作系统下对字节 0a 换行(/n)会处理成

0d 0a回车换行(/r/n),所以结果是34 0d 0a。

解决办法是:用二进制流来打开文件即,

of.open("d://temp",ios_base::out | ios_base::binary);

(经过实践发现C语言下的fopen等文件处理函数和上面的一样)

抱歉!评论已关闭.