gpt4 book ai didi

C++ 等效于从 popen 读取的 fgets

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:04 30 4
gpt4 key购买 nike

我需要处理一些来自标准输出的数据。这是我正在使用的代码:

FILE* in;
in = popen("ls -a", "r");
char line[256]
while (fgets(line, sizeof(line), in) != NULL) {
// do something with line
}

这很好用,但如果行长超过 256 字节就会出现问题。所以现在我尝试了以下但它不是一个好的解决方案:

FILE* in;
in = popen("ls -a", "r");
char line[100000000] // Wow
while (fgets(line, sizeof(line), in) != NULL) {
// do something with line
}

我如何使用 C++ 来避免必须指定行的大小? IE。能够处理任意长度的线?

编辑,getline 不起作用! :=[[

FILE *in;
std::string line;
while(std::getline(in, line))
{
// Says no matching function =((((
}

最佳答案

C++ 解决方案将使用 std::string 而不是 char[]std::getline 而不是 fgets( ),并输入流而不是 FILE *

一个问题是 POSIX 函数 popen() —— 存在各种 C++ 替代方案,等等...

PStreams

#include "pstream.h"
#include <string>
#include <iostream>

int main()
{
redi::ipstream is("ls -a");
std::string line;
while (std::getline(is, line))
{
std::cout << line << std::endl;
}
}

Boost.Process (截至 1.64“正式”part of Boost.org)

#include "boost/process.hpp"
#include <string>
#include <vector>
#include <iostream>

int main()
{
boost::process::context ctx;
ctx.stdout_behavior = boost::process::capture_stream();

std::string exe( "ls" );
std::vector< std::string > args;
args.push_back( "-a" );

boost::process::child c = boost::process::launch( exe, args, ctx);

boost::process::pistream &is = c.get_stdout();

std::string line;
while (std::getline(is, line))
{
std::cout << line << std::endl;
}
}

关于C++ 等效于从 popen 读取的 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182254/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com