如何通过C/ c++从Linux命令中获得输出?并且适用于android

How to get output from Linux command via C/C++? and suitable for android?

本文关键字:输出 android 适用于 何通过 c++ 命令 Linux      更新时间:2023-10-16

我尝试运行一个Linux命令,并使用C/c++代码读取它的输出。我搜索了exec,但是这个不处理输入/输出。

我想要实现的是通过使用这个命令iwconfig来获取有关无线局域网的信息,从C/c++代码调用它。

我还需要一个合适的代码使用它作为lib android使用NDK。

我看到在android开源中他们叫这个函数

你觉得这段代码怎么样?

int wpa_ctrl_request(struct wpa_ctrl *ctrl, const char *cmd, size_t cmd_len,
                 char *reply, size_t *reply_len,
                 void (*msg_cb)(char *msg, size_t len))
                {
        DWORD written;
        DWORD readlen = *reply_len;
if (!WriteFile(ctrl->pipe, cmd, cmd_len, &written, NULL))
    return -1;
if (!ReadFile(ctrl->pipe, reply, *reply_len, &readlen, NULL))
    return -1;
*reply_len = readlen;
return 0;

}

这是链接

您可以尝试运行该命令并将结果输出到文件中,然后读取它

system("iwconfig > temp.txt");
FILE *fp=fopen("temp.txt","w");

我看到在android开源中他们叫这个函数

你觉得这段代码怎么样?

int wpa_ctrl_request(struct wpa_ctrl *ctrl, const char *cmd, size_t cmd_len,
                     char *reply, size_t *reply_len,
                     void (*msg_cb)(char *msg, size_t len))
{
    DWORD written;
    DWORD readlen = *reply_len;
    if (!WriteFile(ctrl->pipe, cmd, cmd_len, &written, NULL))
        return -1;
    if (!ReadFile(ctrl->pipe, reply, *reply_len, &readlen, NULL))
        return -1;
    *reply_len = readlen;
    return 0;
}

这是链接