我正在用 C++ 编写一个程序,它对 Linux 操作系统上当前目录中的所有文件进行一些特殊处理。
所以我正在考虑使用系统调用,例如system("ls")
获取所有文件的列表。
但如何将它存储在我的程序中? (如何将 ls 的输出重定向到我在程序中声明的字符串)
Thanks
共识似乎是不使用“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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)