Kevin Dong
Kevin Dong

Reputation: 5351

How to redirect stdout to a string in ANSI C

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

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

In Unix you would:

  • Create a pipe
  • fork a child process
  • The parent:
    • Closes the writing end of the pipe
    • Starts reading from the pipe
  • The child:
    • Closes the reading end of the pipe
    • Closes stdout
    • dup2's the write-end pipe to fd 1
    • exec's the new program

Upvotes: 1

yegorich
yegorich

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

Related Questions