如何从通过c运行的命令的输出中获取特定数据?

1 c cmd

system("netsh wlan show profile");

我现在使用 c 程序执行此 cmd,我希望输出中显示所有配置文件名称并将其保存在变量(数组)中。如何做到这一点也请详细告诉我,因为我没有c知识,我正在努力学习它。

Dav*_*eri 5

使用波彭

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char *str = "netsh wlan show profile";
    FILE *cmd;

#ifdef _WIN32
    cmd = _popen(str, "r");
#elif __unix
    cmd = popen(str, "r");
#else
#   error "Unknown system"
#endif
    if (cmd == NULL)
    {
        perror("popen");
        exit(EXIT_FAILURE);
    }

    char result[1024];

    while (fgets(result, sizeof(result), cmd))
    {
        printf("output: %s", result);
    }
#ifdef _WIN32
    _pclose(cmd);
#elif __unix
    pclose(cmd);
#endif
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么要声明“popen”和“pclose”函数?它们以及 Windows 的 `_popen` 和 `_pclose` 都在 `stdio.h` 头文件中声明。您不应该自己声明它们。 (3认同)