在 C 中用 popen 逐行获取 stdout 的输出

Grab output of stdout with popen line by line in C

我想逐行读取程序的输出并在每行之后做一些事情(以“\n”结尾)。以下代码片段读取 50 个字符的块并打印输出。在换行符出现之前,我有什么办法可以阅读吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
        FILE* file = popen("some program", "r");
        char out[50];
        while(fgets(out, sizeof(out), file) != NULL)
        {
            printf("%s", out);
        }
        pclose(file);
        
        return 0;
}

fgetc()就是你想要的。您将创建一个缓冲区(静态分配或动态分配),遍历 fgetc() 并测试该值——如果它不是换行符,则将其添加到缓冲区,如果它是换行符,则将其添加到buffer 如果那是你想要的,然后 printf() 缓冲区,然后清除缓冲区并继续循环。

您可以使用 getline() 始终一次阅读整行,无论其长度如何:

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

int main(int argc, char* argv[])
{
        FILE* file = popen("some program", "r"); // You should add error checking here.
        char *out = NULL;
        size_t outlen = 0;
        while (getline(&out, &outlen, file) >= 0)
        {
            printf("%s", out);
        }
        pclose(file);
        free(out);
         
        return 0;
}