如何在c++程序中打开进程并将结果读入ifstream
How to open a process and read the results into an ifstream from within a C++ program?
我正在编写一个可以在Unix环境下运行的c++ 11程序(可移植性不是问题)。目前,我有一个调用两个进程的Makefile,一个向文件写入,另一个从该文件读取。
target:
mkfifo myfile
other_program > myfile &
my_program myfile
由于各种原因,我想从my_program中调用所有这些。看起来popen
很有希望,因为它调用了一个外部进程并提供了一个我可以读取的FILE*。但是,我已经编写的现有文件处理代码使用ifstream:
std::ifstream stream1(argv[1]);
有一个体面的方式来连接popen
的文件* ifstream?我应该用别的东西代替popen
吗?
您可以创建一个从FILE*
读取的流缓冲区。显然,如果您在其他地方使用std::ifstream
而不是创建流,则可能需要更改代码以使用std::istream
,但这应该是一个直接的更改。下面是一个简单的演示,展示了如何创建相应的流缓冲区以及如何使用它:
#include <cstdio>
#include <iostream>
struct FILEbuf
: std::streambuf {
FILEbuf(FILE* fp): fp_(fp) {}
int underflow() {
if (this->gptr() == this->egptr()) {
int size = fread(this->buffer_, 1, int(s_size), this->fp_);
if (0 < size) {
this->setg(this->buffer_, this->buffer_, this->buffer_ + size);
}
}
return this->gptr() == this->egptr()
? traits_type::eof()
: traits_type::to_int_type(*gptr());
}
FILE* fp_;
enum { s_size = 1024 };
char buffer_[s_size];
};
int main()
{
FILEbuf sbuf(popen("ls -l", "r"));
std::istream in(&sbuf);
for (std::string line; std::getline(in, line); ) {
std::cout << line << 'n';
}
}
在过去,我被告知使用popen()
或system()
,因为这些调用被认为是不安全的:这两个调用都会产生一个shell,可以用来劫持它们的行为。另一种方法是使用文件描述符创建流缓冲区,并使用pipe()
、dup()
(或其兄弟之一)、close()
、fork()
和execl()
(或其兄弟之一)直接构建管道。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- ifstream什么都没读
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 当与Windows和Linux下的Ifstream相反的二进制文件时,结果不同
- 如何在c++程序中打开进程并将结果读入ifstream
- 为什么不通过std::cin复制并粘贴到控制台中读取会产生与从std::ifstream读取相同的结果呢