gpt4 book ai didi

c++ - 如何将 linux 命令的输出复制到 C++ 变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:00:39 24 4
gpt4 key购买 nike

我正在从创建以下输出的 C++ 程序中调用 LINUX 命令。我需要将输出的第一列复制到 C++ 变量(比如 long int)。我该怎么做??如果这不可能,我该如何将此结果复制到我可以使用的 .txt 文件中?

编辑

          0 +0
2361294848 +2361294848
2411626496 +50331648
2545844224 +134217728
2713616384 +167772160

我将其存储为一个文件 file.txt,我正在使用以下代码来提取不带 0 的左列以将其存储为整数

string stringy="";
int can_can=0;
for(i=begin;i<length;i++)
{
if (buffer[i]==' ' && can_can ==1) //**buffer** is the whole text file read in char*
{
num=atoi(stringy.c_str());
array[univ]=num; // This where I store the values.
univ+=1;
can_can=1;
}
else if (buffer[i]==' ' && can_can ==0)
{
stringy="";
}
else if (buffer[i]=='+')
{can_can=0;}
else{stringy.append(buffer[i]);}
}

我遇到了一个段错误。可以做什么?

提前致谢。

最佳答案

只需围绕 popen() 创建一个简单的 streambuf 包装器

#include <iostream>
#include <stdio.h>

struct SimpleBuffer: public std::streambuf
{
typedef std::streambuf::traits_type traits;
typedef traits::int_type int_type;

SimpleBuffer(std::string const& command)
: stream(popen(command.c_str(), "r"))
{
this->setg(&c[0], &c[0], &c[0]);
this->setp(0, 0);
}
~SimpleBuffer()
{
if (stream != NULL)
{
fclose(stream);
}
}
virtual int_type underflow()
{
std::size_t size = fread(c, 1, 100, stream);
this->setg(&c[0], &c[0], &c[size]);

return size == 0 ? EOF : *c;
}

private:
FILE* stream;
char c[100];

};

用法:

int main()
{
SimpleBuffer buffer("echo 55 hi there Loki");
std::istream command(&buffer);

int value;
command >> value;

std::string line;
std::getline(command, line);

std::cout << "Got int(" << value << ") String (" << line << ")\n";
}

结果:

> ./a.out
Got int(55) String ( hi there Loki)

关于c++ - 如何将 linux 命令的输出复制到 C++ 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12376198/

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