Sup*_*mes 14
共识似乎不是使用"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;
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*hen 10
我认为你不能使用系统来读取输出.
尝试使用popen.
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
Run Code Online (Sandbox Code Playgroud)
但是,你可能不想这样做ls.两个原因:
readdir),而不是使用shell命令并解析它.ls.我建议你不要打电话ls- 正确地完成工作,opendir/readdir/closedir用来直接读取目录.
代码示例,打印目录条目:
// $ gcc *.c && ./a.out
#include <stdlib.h> // NULL
#include <stdio.h>
#include <dirent.h>
int main(int argc, char* argv[]) {
const char* path = argc <= 1 ? "." : argv[1];
DIR* d = opendir(path);
if (d == NULL) return EXIT_FAILURE;
for(struct dirent *de = NULL; (de = readdir(d)) != NULL; )
printf("%s/%s\n", path, de->d_name);
closedir(d);
return 0;
}
Run Code Online (Sandbox Code Playgroud)