Reputation: 5351
I am a beginner in learning C language :-)
I have searched how to solve this in stackoverflow, but nothing I can understand. :-(
Before posting this thread, I always redirect stdout to a file, and then read it to a string by using 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.
How can I redirect stdout to a string in C Language without redirecting to a tempfile?
Is it possible? Thanks.
Environment:
Windows and GCC
Upvotes: 1
Views: 2764
Reputation: 137398
In Unix you would:
pipe
fork
a child processstdout
dup2
's the write-end pipe to fd 1exec
's the new programUpvotes: 1
Reputation: 4849
The stdout can be redirected via popen routine:
#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() */
...
}
Upvotes: 2