C++中写文件ofstream 的<< 操作符 与C风格的fwrite 的笔记

在某次工作中,调用了某SDK接口,该接口通过一个回调函数返回需要的内容。我们需要的内容是H.264码流,该码流通过一个unsigned char* 变量带回,另外还有一个长度 int length。为了验证该码流能否播放,我将该数据不断地保存在本地,回调函数如下:

1 void CallBack(long Handle, unsigned char* pStream, int* length, void* pUserData);

我通过以下代码写入文件:

...
using namespace std;
ofstream FileStream("D\\stream.raw");
FileStream << pStream;
FileStream.close();

结果写出的文件不可读,就是不正确。但是通过C风格代码却可以:

FILE *pFile = fopen("D:\\stream.raw","a+"); 
fwrite(pStream,sizeof(unsigned char), length, pFile);
fclose(pFile); 

问题出在哪里呢?

在Stack Overflow 中有这样的解释:

In order to write raw binary data you have to use ostream::write. It does not work with the output operators. 

Also make sure if you want to read from a binary file not to use operator>> but instead istream::read.

意思就是,当你写入原始二进制数据的时候只能使用 ostrem::write ;同样,读取的时候,只能使用istream::read.

 这就解释了上述问题出现的原因。

posted @ 2017-12-27 09:35  花园小花匠  阅读(1764)  评论(0编辑  收藏  举报