C传递终端命令并打印答案

C passing terminal commands and print answer

我正在尝试在终端中执行命令并分析结果,但无法将输出写入变量。 我制作了一个示例代码来说明我的问题:

extern char commandResult;

int main()
{
   char commandResult;
   commandResult = system("[ -f /etc/hosts ] && echo "Found" || echo "Not found"");
   printf("result: ");
   printf("%s", commandResult);
   printf("\n");
}

但是输出是这样的:

CMakeCache.txt      Makefile        logo.c
CMakeFiles          pitm            pitm.c
CMakeLists.txt      README.md
LICENSE             cmake_install.cmake
result: (null) <- The output is supposed to be here! :/

我将使用 "switch/case" 或 if/else 块来分析变量,例如

if(commandResult == "Found") {
    printf("Yes");
} else {
    printf("No");
}

所以谁能告诉我如何让我的输出写入变量而不是直接输出?

system 不会 return 输出 命令 你 运行 而只是 return 退出状态。您可能想使用 popen() 来读取您 运行 命令的输出。请参阅链接手册页中的示例。

您还需要使用 strcmp 来比较字符串,而不是 ==