2

I have been using dup and freopen to rerout stdout to a file as below:

fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
freopen("stdout.out", "w", stdout);

What I would like to do would be rerout it to a char[], so that I can manipulate it. obviously this isn't very useful when writing with printf, but when using libraries that write to stdout, it would be helpful to get the output in the code so I can manipulate it, if necessary.

ewok
  • 20,148
  • 51
  • 149
  • 254
  • Why is reading the file into memory unacceptable? – jxh Aug 09 '12 at 16:20
  • @user315052 it just seems like an extra step to write to a file then read from that file immediately later. can the output not be sent directly to the `char[]`? – ewok Aug 09 '12 at 16:22
  • 1
    There is no API to change `stdout` into a memory stream. GNU's libc provides `fmemopen` and `open_memstream`, but they create new streams, and there is no interface to make one stream replace an existing stream. – jxh Aug 09 '12 at 16:24
  • 2
    This is the mirrored version of your question: http://stackoverflow.com/questions/1558772/how-to-get-file-descriptor-of-buffer-in-memory – Emilio Silva Aug 09 '12 at 16:33

1 Answers1

0

Assigning to stdout is not guaranteed to work, but maybe it will work on your platform, otherwise see this answer based on shmem_open, mmap and fmem_open: https://stackoverflow.com/a/25327235/2332068

Sam Liddicott
  • 1,265
  • 12
  • 24