2016-02-05 48 views
-1

...我试图将system(char* command)函数的输出加载/捕获到变量,vector。我可以有任何可能的方法将输出推送到我的矢量?我不想将输出写入文件并再次读取。 示例代码:将系统(char *命令)的输出加载到变量,C++

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <fstream> 
#include <iostream> 
#include <string> 
#include <cstring> 
#include <sstream> 
#include <vector> 


using namespace std; 

int main() 
{ 
    vector <string> dir; 
    system("pwd");//here i used this to print the current directory, and i want to store this out put to my vector. something like...(below) 
    output=output of system("pwd");//this is not a real code,just to notice i want to put the out put to other var and push. 
    dir.push_back(output); 
return 0; 
} 

我能有任何情况下做这个任务,谢谢。

+0

你试过['getcwd'](http://man7.org/linux/man-pages/man2/getcwd.2.html)吗? –

+0

你不能得到'system'执行的进程的输出。你可以用'popen'执行一个命令来获得一个'FILE *',你可以从中读取输出。 – molbdnilo

+0

hello:@BoPersson,感谢您的回放,但getcwd用于捕获当前工作目录,这是我的问题的特定答案。但是如果我有其他shell命令被System()函数检查和执行会怎样。例如。系统(“任何命令”)? –

回答

1

我建议你做这样的:

FILE *fp = popen("fortune","r"); 
char line[200]; 
while(!feof(fp)) { 
fgets(line,200,fp); 
// process here 
} 
pclose(fp); 

如果它真的表现的关键,它可能更好地 使用fork()和管道为孩子 进程的标准输入/输出,以创建子进程写或读。 如果您被构建,可以在这里找到一个例子(http://www.microhowto.info/howto/capture_the_output_of_a_child_process_in_c.html#idp21888)。但popen方法可能是您的案例中最简单直接的方法。