【问题标题】:I am not able to copy the entire binary file我无法复制整个二进制文件
【发布时间】:2012-05-04 00:39:07
【问题描述】:
    ifstream ifile("/home/zuma/xps.mp3", ios::binary | ios::in);
    ofstream ofile("/home/zuma/xxx.mp3", ios::binary | ios::out);

    copy(istream_iterator<unsigned char>(ifile), istream_iterator<unsigned char>(), ostream_iterator<unsigned char>(ofile));

    ifile.close();
    ofile.close();

创建的新文件的字节数少于原始文件的字节数且文件不匹配

【问题讨论】:

  • 请添加输入输出的简短示例。

标签: c++ file stl binary copy


【解决方案1】:

istream_iterator 使用operator&gt;&gt;,它是用空格分隔的(不,以二进制模式打开文件不会改变这种行为)。请改用istreambuf_iterator

istreambuf_iterator<char> in1(ifile), in2;
ostreambuf_iterator<char> out(ofile);
copy(in1, in2, out);

或者,正如 ildjarn 所提到的,您可以复制整个文件而无需输入太多内容:

ofile << ifile.rdbuf();

【讨论】:

  • 更简单,ofile &lt;&lt; ifile.rdbuf(); -- 不需要迭代器。
  • @ildjarn:当然,但如果他想调整它以复制少于整个文件,那将行不通。
  • @user643979 感谢某人提供正确答案的好方法是单击接受按钮。它强调了他们的反应是最有用的(并略微提高了分数,尽管我认为 Benjamin Lindley 并没有因此受到伤害)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 2013-08-04
  • 1970-01-01
  • 2014-04-22
  • 2017-10-18
  • 1970-01-01
相关资源
最近更新 更多