boost::iostream::copy(), inputstream and outstream

2019-03-06 17:13发布

问题:

I have a txt file: gcc-4.7.2.txt : with the data written: Hello This is a test file. Thanks :compressed as gcc-4.7.2.tar.bz2

Now, I run the following code:

#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;
    }
}

While running it the output is:

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

Thanks

What are the characters before Hello ? why is it printing the file name?

I just copied the the in stream 'in' to cout using boost::iostream function.

Why should it only be copied to 'cout' how can I have a different named output stream there ?

回答1:

If you uncompress the compressed tar archive, you get a tar archive!

Tar archive format is described here: https://en.wikipedia.org/wiki/Tar_(computing)#File_format

To show how that works, try this instead:

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

to extract the files