[英]How to redirect stdout to a string in ANSI C
I am a beginner in learning C language :-) 我是学习C语言的初学者:-)
I have searched how to solve this in stackoverflow, but nothing I can understand. 我已经搜索了如何在stackoverflow中解决此问题,但是我无法理解。 :-(
:-(
Before posting this thread, I always redirect stdout to a file, and then read it to a string by using fread
发布此线程之前,我总是将stdout重定向到文件,然后使用
fread
将其读取为字符串
system ("print.exe > tempfile.tmp");
FILE *fp = fopen ( tempfile.tmp , "rb" );
char Str[Buf_Size];
fread (Str,sizeof(char),Buf_Size,fp);
If doing so, it'll waste lots of time in File I/O. 如果这样做,将浪费大量时间在文件I / O中。
How can I redirect stdout to a string in C Language without redirecting to a tempfile? 如何在不重定向到tempfile的情况下将stdout重定向到C语言中的字符串?
Is it possible? 可能吗? Thanks.
谢谢。
Environment: Windows and GCC
环境:
Windows and GCC
In Unix you would: 在Unix中,您将:
pipe
pipe
fork
a child process fork
一个子进程 stdout
stdout
dup2
's the write-end pipe to fd 1 dup2
到fd 1的写端管道 exec
's the new program exec
的新程序 The stdout can be redirected via popen routine: 可以通过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() */
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.