3

I have this program for reading char by char a file and print it out on the screen:

#include<stdio.h>

int main()
{
    unsigned char mychar;
    FILE *fp;
    fp=fopen("test.txt", "r");
    while((mychar = getc(fp))!=EOF)
        printf("%c", mychar);
    fclose(fp);
    return 0;
}

It prints the file but then it continues to loop forever. Can you help me?

7
  • 4
    unsigned char mychar; --> int mychar;
    – BLUEPIXY
    May 7, 2016 at 22:49
  • Yes, thanks; maybe char is better.
    – user6304861
    May 7, 2016 at 22:53
  • char is wrong. Because char is signed char or unsigned char.
    – BLUEPIXY
    May 7, 2016 at 22:55
  • 2
    Actually look at the documentation for getc. It returns an int actually, and that is the type that should be used.
    – Zan Lynx
    May 7, 2016 at 23:02
  • 1
    n1570 6.2.5 Types p15 The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char
    – BLUEPIXY
    May 7, 2016 at 23:53

1 Answer 1

6

EOF have value -1 So, why do you declare mychar as unsigned char?

Please change with this:

int main()
{
    int mychar;
    FILE *fp;
    fp=fopen("test.txt", "r");
    while((mychar = getc(fp))!=EOF)
        printf("%c", mychar);
    fclose(fp);
    return 0;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy