gpt4 book ai didi

c++ - 如何将系统调用的输出重定向到 C/C++ 程序内部?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:51 26 4
gpt4 key购买 nike

我正在用 C++ 编写一个程序,它对 Linux 操作系统当前目录中的所有文件进行一些特殊处理。

所以我在考虑使用系统调用,例如 system("ls") 来获取所有文件的列表。

但是如何将它存储在我的程序中呢? (如何将 ls 的输出重定向为我在程序中声明的字符串)

谢谢

最佳答案

共识似乎是不使用“ls”。但是,对于任何对执行此功能感兴趣的人:

/**
* Execute a command and get the result.
*
* @param cmd - The system command to run.
* @return The string command line output of the command.
*/
string GetStdoutFromCommand(string cmd) {

string data;
FILE * stream;
const int max_buffer = 256;
char buffer[max_buffer];
cmd.append(" 2>&1"); // Do we want STDERR?

stream = popen(cmd.c_str(), "r");
if (stream) {
while (!feof(stream))
if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
pclose(stream);
}
return data;
}

关于c++ - 如何将系统调用的输出重定向到 C/C++ 程序内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2655374/

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