0

我是学习 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

4

2 回答 2

1

在 Unix 中,你会:

  • 创建一个pipe
  • fork一个子进程
  • 家长:
    • 关闭管道的写入端
    • 从管道开始读取
  • 孩子:
    • 关闭管道的读取端
    • 关闭stdout
    • dup2是 fd 1 的写端管道
    • exec是新节目
于 2013-10-10T06:51:46.067 回答
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() */
   ...
}
于 2013-10-10T06:52:12.850 回答