1

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

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62
  • 2
    If you're on a POSIX-ish environment, you can read the output of `print.exe` via `FILE *fp = popen("print.exe", "r");`. If you're on a Microsoft-ish system, you may be able to use `_popen()` in place of `popen()`. – Jonathan Leffler Oct 10 '13 at 06:51
  • @Jonathon Reinhart in windows – Kevin Dong Oct 10 '13 at 07:12

2 Answers2

2

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() */
   ...
}
yegorich
  • 4,653
  • 3
  • 31
  • 37
1

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
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328