c++读写二进制文件

2014-11-24 03:30:58 · 作者: · 浏览: 0

曾经看过一个帖子http://pnig0s1992.blog.51cto.com/393390/563152,文中说c++读写二进制文件关键在于接口函数,用什么模式打开没有关系,我觉得那样讲是不对的。不过文章看一下也可以。

c++读写二进制文件,在windows与linux下可能会有不同的效果。本人写的一个小例子在linux下写入二进制数据正常,而在windows下面写入数据的过程中,竟然自动添加了0x25等等一些无意义的字节,找了好久才发现这个bug。

下面是正确的写法

void TestWriteBinary()
{
	const char *pcwritefile = "fileBinary.txt";

	ofstream ofs;
	ofs.open(pcwritefile, ios::out | ios::binary);
	assert(ofs.is_open());
	
	for (int i = 0; i < 100; ++i)
	{
		HashKey_S stHashKey;
		stHashKey.uifirsthash = 1;
		stHashKey.uisecondhash = 2;
		ofs.write((const char*)(&stHashKey), sizeof(stHashKey));
	}
	ofs.close();
}

错误的写法是这样的(在linux下工作正常,windows下异常)

void TestWriteBinary()
{
	const char *pcwritefile = "fileBinary.txt";

	ofstream ofs;
	ofs.open(pcwritefile, ios::out);
	assert(ofs.is_open());
	
	for (int i = 0; i < 100; ++i)
	{
		HashKey_S stHashKey;
		stHashKey.uifirsthash = 1;
		stHashKey.uisecondhash = 2;
		ofs.write((const char*)(&stHashKey), sizeof(stHashKey));
	}
	ofs.close();
}

仅仅是在打开文件的时候,没有加ios::binary而已。


同样在读文件的同时,也一定要加上ios::binary,用read读文件即可。

下面是c++读写二进制的一些基础知识,写的不错:http://blog.csdn.net/kingstar158/article/details/6859379