如何在Linux上的c++中将数据管道到bzip2中并从其标准输出中获得结果数据?
How would I pipe data into bzip2 and get the resulting data from its stdout in C++ on Linux?
我正在考虑开始为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
你当然不需要一个字符一个字符地读取数据,但我试图让这个例子保持简单。
相关文章:
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 使用提升过程获取 shell 命令的标准输出
- 将标准输出重定向到ostream
- 如何在C++中执行命令并获取命令的返回代码标准输出和标准
- 尝试从 txt 文件中读取两条数据并输出它们 [C++]
- 在程序执行期间从标准输出重定向到自定义流
- 标准输出C++意外行为
- 防止 qDebug() 写入标准输出
- 自定义堆栈上 std::string 数据的输出
- C++ - <<运算符重载,链表 - 地址而不是标准输出
- 有没有办法知道C++中将打印到标准输出的大小?
- 最后推迟标准输出
- 使用文件和结构读取数据并输出数据
- 得到~对标准输出没有回应~在黑客排名问题上
- Win32 GUI C(++) 应用将标准输出和标准输出重定向到磁盘上的同一文件
- 在标准输出中执行打印会导致数组中随机分配值
- 通过C++从标准输出中的一些打印数据中提取特定值
- c++在标准输入上写入数据,并从标准输出中获得输出
- 如何在Linux上的c++中将数据管道到bzip2中并从其标准输出中获得结果数据?
- 我如何捕获数据,这将被发送到标准输出在c++