stdin gets closed if input has been redirected to a file say.
> I don't know what size of input to expect.
Which is why you typically read a file using a fixed buffer and a while loop.
Code:
#include <stdlib.h>
#include <stdio.h>
int main ( ) {
char buff[50];
ssize_t n;
int total = 0;
printf("Before\n");
while ( ( n = fread(buff, 1, sizeof buff - 1, stdin) ) > 0 ) {
buff[n] = '\0';
printf("+++%s+++\n",buff);
total += n;
}
printf("After - read %d bytes\n", total);
return 0;
}
Run on itself, it looks like this
Code:
$ ./a.out < foo.c
Before
+++#include <stdlib.h>
#include <stdio.h>
int main +++
+++( ) {
char buff[50];
ssize_t n;
int +++
+++ total = 0;
printf("Before\n");
while +++
+++( ( n = fread(buff, 1, sizeof buff - 1, stdin) ) +++
+++> 0 ) {
buff[n] = '\0';
printf("+++%s+++\+++
+++n",buff);
total += n;
}
printf("After +++
+++- read %d bytes\n", total);
return 0;
}
+++
After - read 337 bytes
Inside the loop, you either process what you've read so far, or allocate some space to store it for later.