1

Is there any way to redirect stdout file stream (C stdout) to a buffer in Windows?

The only thing that worked for me was:

FILE *fp = freopen("output.txt", "w", stdout);
printf("Hello\n");
fclose(fp);

but I always have to read the file back in order to get the buffer content. Any way to directly redirect it to a memory buffer?

Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • Does it have to be in C code? Else, just redirect with > when starting the program – deviantfan Jan 27 '14 at 11:59
  • Yes, in the code unfortunately. – Marco A. Jan 27 '14 at 12:00
  • I'd like to directly redirect stdout into a char array and not writing it to a file and then reading it into a char array. – Marco A. Jan 27 '14 at 12:02
  • I guess here you have an example http://stackoverflow.com/a/617158/2549281 – Dabo Jan 27 '14 at 12:38
  • 1
    You can replace all `printf`s by `myprintf` where `myprintf` would be a function similar to `fprintf` but writing output to a buffer. `myprintf` would essentially use [vsprintf](http://www.cplusplus.com/reference/cstdio/vsprintf/) to get the output into a char buffer and then to your memory buffer. – Jabberwocky Jan 27 '14 at 12:42
  • 1
    Assuming your output does not get too large, you might use setvbuf() to enable full buffering to a buffer guaranteed to be large enough to hold all your output. Be sure to never call fflush(). You might run into an implementation-defined maximal buffer size, though. – Chris Jan 27 '14 at 13:41
  • I eventually implemented @MichaelWalz solution. Make it an answer and I'll accept it. – Marco A. Jan 29 '14 at 19:43

1 Answers1

2

You can replace all printfs by myprintf where myprintf would be a function similar to fprintf but writing output to a buffer. myprintf would essentially use vsprintf to get the output into a char buffer and then to your memory buffer.

Here is a very simple and naive implementation of the concept with no error checking just to give you an idea.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

void myprintf(char *mybuffer, const char *format, ...)
{
  va_list args;
  va_start (args, format);

  char tempbuffer[100] ;
  vsprintf (tempbuffer, format, args);

  strcat(mybuffer, tempbuffer) ;
  va_end (args);
}

int main()
{
  char buffer[100] ;
  buffer[0] = 0 ;

  myprintf (buffer, "Hello world!\n") ;
  myprintf (buffer, "Hello %s %d", "world", 123) ;

  printf (buffer) ; 
  return 0 ;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115