使用istream从命名管道读取 [英] using istream to read from named pipe

查看:80
本文介绍了使用istream从命名管道读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用c ++(stl)从命名管道(mkfifo)中读取 使用流-因此没有为读取操作预先定义char *buffer[MAX_SIZE]?

Is it possible to read from named pipe (mkfifo) using c++ (stl) using a stream - thus not defining in advance char *buffer[MAX_SIZE] for the read operation?

我想读到缓冲区结束,然后将结果放入std::string.

I want to read till the buffer ends and put the result into std::string.

(当前方法:bytes = read(fd, buffer, sizeof(buffer));需要预先分配某种缓冲区.)

(Current method: bytes = read(fd, buffer, sizeof(buffer)); requires allocation some kind of buffer in advance.)

推荐答案

使用mkfifo创建的命名管道的行为类似于常规文件.因此,可以使用std::ifstreamstd::ofstream来访问它们:

Named pipes created with mkfifo behave like regular files. Thus they can be accessed using std::ifstream and std::ofstream:

#include <fstream>
#include <iostream>

int main(int, char** argv) {
    std::ifstream file{argv[1]};
    std::string line;
    std::getline(file, line);
    std::cout << line << '\n';
}

运行:

mkfifo foobar
./main foobar

以及其他地方:

echo 'Hello world!' > foobar

…这将导致./main打印"Hello world!"到标准输出.

… this will cause ./main to print "Hello world!" to the standard output.

这篇关于使用istream从命名管道读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆