【问题标题】:Grab output of stdout with popen line by line in C在C中逐行获取带有popen的stdout的输出
【发布时间】:2020-12-20 16:19:26
【问题描述】:

我想逐行读取程序的输出,并在每一行之后做一些事情(以“\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;
}

【问题讨论】:

    标签: c output line stdout popen


    【解决方案1】:

    您可以使用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;
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 2014-11-28
        • 1970-01-01
        • 2015-02-05
        • 1970-01-01
        相关资源
        最近更新 更多