gpt4 book ai didi

c++ - 将系统(char* 命令)的输出加载到变量,c++

转载 作者:太空宇宙 更新时间:2023-11-04 05:00:17 25 4
gpt4 key购买 nike

...正在尝试加载/捕获 system(char* command) 的输出函数到变量,a vector 。我可以有任何可能的方法将输出推送到我的 vector 吗?我不想将输出写入文件并再次读取它。示例代码:

#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;
}

我可以有任何场景来完成这项任务吗,谢谢。

最佳答案

我建议这样做:

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 方法可能是您的情况中最简单、最直接的方法。

关于c++ - 将系统(char* 命令)的输出加载到变量,c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35219017/

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