将系统命令的输出存储到c中的本地char数组中 [英] Store output of system command into local char array in c
问题描述
有什么方法可以将系统命令的输出存储到char数组中,因为系统命令仅返回int.
Is there any way to store output of system command into char array, since system command is returning only int.
推荐答案
无法检索 system(3)
的输出.好的,您可以将执行的任何命令的输出重定向到文件,然后打开并读取该文件,但是更明智的方法是使用 popen(3)
.
There's no way to retrieve the output of system(3)
. Well, you could redirect the output of whatever command is executed to a file and then open and read that file, but a more sane approach is to use popen(3)
.
popen(3)
替换了 system(3)
,它允许您读取命令的输出(或者,根据传递给它的标志,您可以写入命令的输入).
popen(3)
replaces system(3)
and it allows you to read the output of a command (or, depending on the flags you pass it, you can write to the input of a command).
这是一个执行 ls(1)
并显示结果的示例:
Here's an example that executes ls(1)
and prints the result:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *ls_cmd = popen("ls -l", "r");
if (ls_cmd == NULL) {
fprintf(stderr, "popen(3) error");
exit(EXIT_FAILURE);
}
static char buff[1024];
size_t n;
while ((n = fread(buff, 1, sizeof(buff)-1, ls_cmd)) > 0) {
buff[n] = '\0';
printf("%s", buff);
}
if (pclose(ls_cmd) < 0)
perror("pclose(3) error");
return 0;
}
这篇关于将系统命令的输出存储到c中的本地char数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!