I have been crunching my brains on this one all day. I use this library that
creates output I want, but it can only write it to a file or the stdout. The
problem is that I don't want to use the filesystem (permissions, latency
through NFS, etc, etc), but a memory buffer. I've been looking for a way to
redirect stdout to a buffer that I manage myself. Obviously I considered
setbuf (from stdio.h), but then I'ld still have to redirect output to
/dev/null on posix systems and to something I'm not too sure about on
non-posix systems.
I'ld really prefer an ANSI C solution to this problem. Basically what I want
is the following:
int main(void)
{
char buf[BUFFER_SIZE];
FILE *stdout_bkp, *stdout_rep;
some_function_to_backup_a_stream(stdout, stdout_bkp);
stdout_rep = some_function_to_create_a_FILEPTR_to_a_memptr(&buf );
some_function_to_redirect_a_stream(stdout_rep, stdout);
my_library_function();
some_function_to_redirect_a_stream(stdout_bkp, stdout)
fclose(stdout_rep);
my_function_to_do_something_with_the_output(&buf);
return 0;
}
I tried stuff like (open_memstream is part of the GNU C lib, which I'ld
rather not use, if ANSI has alternatives):
int main(void)
{
char *buf;
size_t size;
int stdout_bkp, stdout_rep = open_memstream(&buf, &size);
stdout_bkp = dup(1);
dup2(fileno(stdout_rep), 1);
printf("This should end up in the buffer\n");
libfunc();
fprintf(stdout_rep, "Just to make sure that SOMETHING ends up in the
buffer");
fclose(stdout_rep);
fprintf(stderr, "Result in buffer:\n%s\n", buf);
return 0;
}
This results in the output:
Result in buffer:
Just to make sure that SOMETHING ends up in the buffer
Does anyone have any clue as to what I want and wether it is possible?
Regards,
Philip