How to Read from stdin in C

Reading from stdin in c - is exactly like reading from a file. (In unix philosophy - everything is a file after all). This means that the how to read a file program is almost the same when reading stdin.

stdin behaves exactly like a FILE* opened with fopen - to the os and the c runtime there is no difference. This means that apart from opening the file (stdin is implicitly opened for us) the code is exactly the same as before.

#include <stdio.h>
int main(int argc, char **argv)
{
  char buf[BUFSIZ];
  while(NULL != fgets(buf, sizeof buf, stdin)) {
    printf("%s", buf);
  }

}

Related Posts