将系统的输出(char *命令)加载到变量,C ++ [英] Loading output of System (char* command) to variable, c++
问题描述
...正在尝试加载/捕获系统(char *命令)的输出函数作为变量,即 vector .有什么办法可以将输出推到我的向量上?我不想将输出写入文件并再次读取.示例代码:
...Am trying to load/capture the output of system(char* command) function to a variable, a vector. can i have any possible way to push the output to my vector? I don*t want to write the output to file and read it again. Sample code:
#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;
}
谢谢,我能在任何情况下完成此任务吗.
Can i have any scenario to do this task, thanks.
推荐答案
我建议这样做:
FILE *fp = popen("fortune","r");
char line[200];
while(!feof(fp)) {
fgets(line,200,fp);
// process here
}
pclose(fp);
如果它确实对性能至关重要,那么最好使用fork()和管道为该孩子的stdin/stdout创建一个孩子进程写入或读取的过程.可以在此处找到一个示例(http://www.microhowto.info/howto/如果您已接受测试,则为capture_the_output_of_a_child_process_in_c.html#idp21888 ).但是popen方法可能是您所用的最简单直接的方法.
If it's really performance critical it's probably better to create a child process using fork() and pipes for stdin/stdout of that child process to write or read from. An example of this could be found here (http://www.microhowto.info/howto/capture_the_output_of_a_child_process_in_c.html#idp21888) if you're intested. But the popen method is probably the most simple and straightforward one in your case.
这篇关于将系统的输出(char *命令)加载到变量,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!