Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect output from stdout to a string?

Tags:

c

redirect

stdout

in C i want to redirect the output of a process from stdout to write to a "shared memory segment" which can be thought of as a char array or a string with a pointer
i know that there is dup2 but it takes file discriptors as argument not a pointer to an array. is there any way to redirect it to a string?

like image 683
CSawy Avatar asked Jan 20 '13 19:01

CSawy


2 Answers

char string[SIZE];
freopen("/dev/null", "a", stdout);
setbuf(stdout, string);

see freopen and setbuf for their definitions

like image 181
sr01853 Avatar answered Oct 01 '22 21:10

sr01853


This should work on UNIX systems:

// set buffer size, SIZE
SIZE = 255;

char buffer[SIZE];
freopen("/dev/null", "a", stdout);
setbuf(stdout, buffer);
printf("This will be stored in the buffer");
freopen ("/dev/tty", "a", stdout);
like image 32
setnoset Avatar answered Oct 01 '22 20:10

setnoset