如何在Linux上的c++中将数据管道到bzip2中并从其标准输出中获得结果数据?

How would I pipe data into bzip2 and get the resulting data from its stdout in C++ on Linux?

本文关键字:数据 标准输出 结果 bzip2 管道 Linux 上的 c++      更新时间:2023-10-16

我正在考虑开始为Linux开发一个库,它将为应用程序开发人员提供一个虚拟文件系统,其中文件将存储在存档中,存档中的每个文件将被单独压缩,以便对开发人员、CPU和硬盘驱动器来说,检索单个文件是一项非常简单的任务。(不需要复杂的API,不需要解压缩数据,只需要相关的数据,并且只检索相关的数据,而不是整个存档)

在Linux上使用c++之前,我已经使用popen来检索命令的标准输出,但是我不知道如何管道数据输入和获取数据输出,一些bzip2特定的技巧会很好。几年前我写过类似的东西,但它包含了一个霍夫曼压缩库作为dll,而不是必须管道数据并使用标准工具。

bzip2有一个库接口——这可能比调用子进程更容易。

我建议你也看看GIO库,它已经是一个"应用程序开发人员的虚拟文件系统";与从头开始编写一个库VFS相比,扩展它来做你想做的事情可能要少得多。

看看Boost IOStreams

作为示例,我从命令行创建了以下文件:
$ echo "this is the first line" > file
$ echo "this is the second line" >> file
$ echo "this is the third line" >> file
$ bzip2 file 
$ file file.bz2 
file.bz2: bzip2 compressed data, block size = 900k

然后使用boost::iostreams::filtering_istream读取名为file.bz2.

的解压缩bzip2文件的结果。
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <iostream>
namespace io = boost::iostreams;
/* To Compile:
g++ -Wall -o ./bzipIOStream ./bzipIOStream.cpp -lboost_iostreams
*/
int main(){
    io::filtering_istream in;
    in.push(io::bzip2_decompressor());
    in.push(io::file_source("./file.bz2"));
    while(in.good()){
        char c = in.get();
        if(in.good()){
            std::cout << c;
        }
    }
    return 0;
}

执行该命令的结果为解压后的数据。

$ ./bzipIOStream 
this is the first line
this is the second line
this is the third line

你当然不需要一个字符一个字符地读取数据,但我试图让这个例子保持简单。