The code is correct (apart from the #include "string.h"
which should be
#include <string.h>
)1, the problem is that when you press
Ctrl+D on your terminal, your terminal might write
something on the terminal, which you cannot control and this output might be
^D
After fgets
returns NULL
, you do printf("%d \n", found);
which prints the '1'.
But because there was ^D
on the terminal, the ^
was replaced by the '1' and
you end up with:
1D
Change your last printf
to this:
printf("\n\n%d \n, found);
And you might see only a '1' in the next lines of the output.
This has nothing to do with your C program, it's the behaviour of your terminal.
My terminal for example doesn't print when pressing Ctrl+D,
but when pressing Ctrl+C I get ^C
. There's nothing you
can do.
edit
With There's nothing you can do I mean that you cannot control the way the
terminal from you C program without calling external tools like stty
. While
this might solve your problem, you are loosing portability.
However, before you start you program, you can configure your terminal using a
program like stty
. See Jonathan Leffler's answer for more info on that.
Fotenotes
1As Jonathan Leffler points out in the comments, using quotes instead
of angle brackets for system headers is not an error per se. For example my GCC
compiler searches in the same directory of the compiled file for headers that
were included with quotes. But in general, it's a good practice to include the
header files included provided by your system with angle brackets.