【问题标题】:boost::iostream::copy(), inputstream and outstream output explanantionboost::iostream::copy()、inputstream和outstream输出解释
【发布时间】:2015-09-27 19:53:17
【问题描述】:

我有一个 txt 文件: gcc-4.7.2.txt :写入数据: 你好 这是一个测试文件。 谢谢 : 压缩为 gcc-4.7.2.tar.bz2

现在,我运行以下代码:

#include <sstream>
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/filesystem.hpp>

int main()
{
    using namespace std;
    using namespace boost::iostreams;

    char filename[] = "gcc-4.7.2.tar.bz2";

    if (!boost::filesystem::exists(filename))
    {
        cout << "Can't find " << filename << ". Expect errors to follow! " << endl;
    }

    ifstream file(filename, ios_base::in | ios_base::binary);
    filtering_streambuf<input> in;
    filtering_streambuf<output> out;

    in.push(bzip2_decompressor());
    in.push(file);

    try
    {
        //cout <<  "in_file:" << in << endl;
        boost::iostreams::copy(in, cout);
        //boost::iostreams::copy(in, out);
        //cout << cout << endl;
        //boost::iostreams::copy(in, compressed_string);
        //cout << "Copied" << compressed_string << "  " <<  in.str() << endl;
    }
    catch (const bzip2_error& exception)
    {
        cout << "catchblock" << endl;
        cout << exception.what() << endl;
        int error = exception.error();
        if (error == bzip2::data_error)
        {
            cout << "compressed data stream is corrupted";
        }
        else if (error == bzip2::data_error_magic)
        {
            cout << "compressed data stream does not begin with the 'magic' sequence 'B' 'Z' 'h'";
        }
        else if (error == bzip2::config_error)
        {
            cout << "libbzip2 has been improperly configured for the current platform";
        }
        else
        {
            cout << "Error: " << error;
        }
        cout << endl;
    }
}

运行时输出为:

dev4@sun-desktop:~/readerwriter$ ./test1 
gcc-4.7.2.txt0000644000175100001440000000004312547435102011603 0ustar  dev4usersHello 
This is a test file.

谢谢

Hello 前面的字符是什么? 为什么要打印文件名?

我刚刚使用 boost::iostream 函数将输入流 'in' 复制到 cout。

为什么它只应该被复制到'cout'我怎样才能在那里有一个不同的命名输出流?

【问题讨论】:

标签: c++ c++11 gcc boost iostream


【解决方案1】:

如果你解压压缩的 tar 存档,你会得到一个 tar 存档!

Tar 存档格式在此描述:https://en.wikipedia.org/wiki/Tar_(computing)#File_format

为了展示它是如何工作的,试试这个:

dev4@sun-desktop:~/readerwriter$ ./test1 | tar x

提取文件

【讨论】:

  • 我的问题是为什么 boost::iostreams::copy(in, cout); codeline 会打印出各种东西吗?这只是一个复制命令。如果我有 boost::iostreams::copy(in, abc); 会有什么不同?而不是 cout 那里?
  • std::cout 是与标准输出相关的 ostream...所以你复制到它的东西显然会被打印出来。这就是copying的意思(还记得你抄作业/笔记的时候吗?)。如果您使用另一个流,例如 abc,那么显然 那个 流将接收存档内容
  • 哦。我刚刚意识到您可能完全错过了我回答的重点。 “为什么copy...打印出各种东西” - 答:它打印文件的内容。 “各种东西”文件的内容。这就是我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 2011-11-19
  • 2011-09-29
  • 2023-03-18
  • 2012-05-19
  • 2014-02-17
  • 2011-05-03
相关资源
最近更新 更多