I am trying read stdout of my own program into 2 arrays like this
#include<stdio.h>
int main ()
{
char arr[100]={0};
char arr2[100]={0};
printf("Hello world\n"); // This writes to stdout
fgets( arr, 80, stdout );
fseek ( stdout, 0, SEEK_SET );
fgets ( arr2, 80, stdout );
printf ("First array is %s\n", arr );
printf ("Second array is %s\n", arr2 );
return 0;
}
The output is not what I expect. That is both the arrays are empty instead of containing Hello World as I expected.
I went through this post which suggests dealing with pipes to accomplish what I want but doesn’t tell me why my above code doesn’t work?
EDIT: Though it would be nice to know alternatives to make the above work as it should, I am more curious on the problems involved in reading stdout of the same program
Not every file is seekable, readable or writeable. Stdout is usually a kind that can’t be read back.
Most likely,
stdoutwill be a pipe. In that case, your program holds the writable end, and someone else holds the readable end. The pipe implementation just transfers data and does not keep it; once it has been read at the other end, there is no way to get it back.If you want a file that can be read back, create a regular temporary file, or your own pipe, and use
fprintf/fscanfinstead ofprintf/scanf. Alternatively, dofreopenon stdout to reassign it to another file/pipe, thenprintfwill operate on that new file.