[英]How to copy the output of linux command to a C++ variable
我正在從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)
您可能正在尋找的popen
。 嘗試
man popen
。
或者看這個小例子:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
FILE *in;
char buff[512];
if(!(in = popen("my_script_from_command_line", "r"))){
return 1;
}
while(fgets(buff, sizeof(buff), in)!=NULL){
cout << buff; // here you have each line
// of the output of your script in buff
}
pclose(in);
return 0;
}
您可能想使用popen
執行命令。 這將為您提供一個FILE *
,您可以從中讀取其輸出。 從那里,您可以使用以下內容解析出第一個數字:
fscanf(inpipe, "%d %*d", &first_num);
就像從文件中讀取時一樣,通常會重復執行直到收到文件結束指示,例如:
long total = 0;
while (1 == fscanf(inpipe, "%l %*d", &first_num))
total = first_num;
printf("%l\n", total);
不幸的是,由於平台API是為C編寫的,所以這並不容易。以下是一個簡單的工作示例:
#include <cstdio>
#include <iostream>
int main() {
char const* command = "ls -l";
FILE* fpipe = popen(command, "r");
if (not fpipe) {
std::cerr << "Unable to execute commmand\n";
return EXIT_FAILURE;
}
char buffer[256];
while (std::fgets(buffer, sizeof buffer, fpipe)) {
std::cout << buffer;
}
pclose(fpipe);
}
但是,我建議將FILE*
句柄包裝在RAII類中以進行資源管理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.