【问题标题】:How to redirect stdout to a string in ANSI C如何将标准输出重定向到 ANSI C 中的字符串
【发布时间】:2013-10-10 06:45:34
【问题描述】:

我是学习 C 语言的初学者 :-)

我已经在 stackoverflow 中搜索了如何解决这个问题,但我无法理解。 :-(

在发布这个帖子之前,我总是将标准输出重定向到一个文件,然后使用fread将其读取到一个字符串

system ("print.exe > tempfile.tmp");
FILE *fp = fopen ( tempfile.tmp , "rb" );
char Str[Buf_Size];
fread (Str,sizeof(char),Buf_Size,fp);

如果这样做,会在文件 I/O 上浪费大量时间。

如何在不重定向到临时文件的情况下将标准输出重定向到 C 语言中的字符串?

有可能吗?谢谢。

环境: Windows and GCC

【问题讨论】:

  • 如果您在 POSIX 环境中,您可以通过FILE *fp = popen("print.exe", "r"); 读取print.exe 的输出。如果您使用的是 Microsoft 系统,则可以使用 _popen() 代替 popen()
  • @Jonathon Reinhart 在窗口中

标签: c string redirect stdout


【解决方案1】:

标准输出可以通过popen 例程重定向:

#include <stdio.h>
...


FILE *fp;
int status;
char path[PATH_MAX];


fp = popen("ls *", "r");
if (fp == NULL)
    /* Handle error */;


while (fgets(path, PATH_MAX, fp) != NULL)
    printf("%s", path);


status = pclose(fp);
if (status == -1) {
    /* Error reported by pclose() */
    ...
} else {
    /* Use macros described under wait() to inspect `status' in order
   to determine success/failure of command executed by popen() */
   ...
}

【讨论】:

    【解决方案2】:

    在 Unix 中你会:

    • 创建pipe
    • fork 一个子进程
    • 父级:
      • 关闭管道的写入端
      • 开始从管道读取
    • 孩子:
      • 关闭管道的读取端
      • 关闭stdout
      • dup2 是 fd 1 的写端管道
      • exec的新程序

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    相关资源
    最近更新 更多