First error
A big problem here...
char c = getc(fp);
See that? That's a big problem. Why? Let's look at the definition of getc()
...
int getc(FILE *stream);
Yes, it returns int
not char
, and that is Important with a capital I and a bold font. The getc()
function (or macro) signals EOF with the EOF
, which is usually -1, and therefore becomes 0xff
when stored in a char
.
Always use int
with getc()
.
int c = getc(fp);
if (c == EOF) {
...
}
Second error
Well, why are we getting EOF? Because getc()
is called twice instead of once...
while ((c = getc(fp)) != EOF) {
c = getc(fp); // <-- should not be there
...
}
Third error
This code is also wrong:
char c = ...;
printf("[%d] [%s]\n", c, &c);
Yes, &c
has type char *
but that does not mean you can print it out with %s
. The %s
specifier is strictly for NUL-terminated strings. Either use %c
, or continue using %s
and NUL-terminate the string you pass it.
char c = ...;
printf("[%d] [%c]\n", c, c);
Or...
char c = ...;
printf("[%d] [%s]\n", c, (char[]){c, '\0'});