Reputation: 28525
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
Upvotes: 2
Views: 2925
Reputation: 1
I suggest you to use gotoxy, its a very simple command where you place coordinates of the position of the stdout.
COORD coord={0,0};
void gotoxy(int x,int y){
coord.X=x;coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
Upvotes: 0
Reputation: 24439
Not every file is seekable, readable or writeable. Stdout is usually a kind that can't be read back.
Most likely, stdout
will 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
/fscanf
instead of printf
/scanf
. Alternatively, do freopen
on stdout to reassign it to another file/pipe, then printf
will operate on that new file.
Upvotes: 5
Reputation: 1779
This is the correct code:
#include<stdio.h>
int main ()
{
char arr[100]={0};
char arr2[100]={0};
int i,j;
printf("Hello world\n"); // This writes to stdout
fgets( arr, 80, stdin );
fgets ( arr2, 80, stdin );
printf("\n");
for(i=0; i<80; i++){
printf ("%c", arr[i]);
}
for(j=0; j<80; j++){
printf ("%c", arr2[j]);
}
return 0;
}
1) fgets has to read from stdin and not from stdout :)
2) you cannot print all the array with printf array
, you must iterate into it with a for
cicle
Upvotes: 0