All of the input functions will give you an end of file indication when the file is finished. For example:
#include <stdio.h>
int main(void) {
int count = 0;
while (getchar() != EOF)
++count;
printf("There were %d characters.\n", count);
return 0;
}
will count the characters in the input stream:
pax> ./testprog <testprog.c
There were 169 characters.
pax> echo -n hello | ./testprog
There were 5 characters.
If you're using fgets
(as seems clear from your update), that also allows easy detection:
#include <stdio.h>
static char buff[1000];
int main(void) {
int count = 0;
while (fgets(buff, sizeof(buff), stdin) != NULL)
++count;
printf("There were %d lines.\n", count);
return 0;
}
Running that will count the lines:
pax> ./testprog <testprog.c
There were 12 lines.
You can see in both cases that the end of file is detected correctly using the input redirection or pipe methods. If you're running your code reading from the terminal, you just have to indicate end of file using the facilities your environment provides.
That's usually CTRL-D at the start of the line in UNIX-like operating systems, or CTRL-Z at the start of the line for Windows:
pax> ./testprog
this has
two lines
<Ctrl-D pressed (I run Linux)>
There were 2 lines.