Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop never stops

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?


1 Answers

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;
}
like image 54
granmirupa Avatar answered Feb 28 '26 18:02

granmirupa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!