zoukankan      html  css  js  c++  java
  • 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.

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

  • 相关阅读:
    Python函数高级
    Python 2和3的区别
    GIL,python全局解释器锁
    Python中的 list
    python中的单例
    新式类和经典类
    整理的排序算法
    Python的双下划方法
    Python 中闭包函数和装饰器
    面向对象,特性之继承
  • 原文地址:https://www.cnblogs.com/gardenofhu/p/8124206.html
Copyright © 2011-2022 走看看