I am a bit confused regarding the implementation of stdin. What exactly is it? Is it a pointer? I tried to print the size of stdin using sizeof on a 64 bit machine and got 8. I even de-referenced it using *stdin in the %s specifier and got the not used characters in the input stream( all of them). But if I compare its de referenced value inside if I get an error. I know its an input stream. But how is it implemented?
Here is a sample:
#include<stdio.h>
#include<stdlib.h>
int main(){
char a[10];
fgets(a,10,stdin);
printf("a: %s",a);
printf("\nstdin: %s",*stdin);
//if(*stdin=="foo"){
// printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help
printf("\nSize of stdin: %d\n",sizeof(stdin));
if(stdin!=NULL){
printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
}
if(!feof(stdin)){
printf("\nThis statement is also always reached");
}
}
When I input
foobar1234567890
I get the result:
a: foobar123
stdin: 4567890
Size of stdin: 8
This statement is always reached
This statement is also always reached
And when I input
foobar
I get the output
a: foobar
stdin:
Size of stdin: 4
This statement is always reached
This statement is also always reached
I understand that stdin is kind of a FILE pointer, but I don't clearly get it. Could anyone explain the above outputs?
stdin
is a pointer of type FILE *
. The standard does not restrict the implementation beyond this, the details of what FILE
is is entirely up to your compiler. It could even be an incomplete type (opaque).
Of course, trying to print a FILE
with %s
causes undefined behaviour (unless FILE
is a typedef for char *
or similar, which it almost certainly is not).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With