In: Computer Science
I need a brief text file to explain why the program “filesize1v.c” gets stuck in the “do/while” loop (i.e., explain why “ch != EOF” is always true) ??
example.txt :
hello ÿhello everyone.
_________________
//filesize1v.c #include #include
int main(int argc, char *argv[]){ FILE *fd; unsigned char ch; //what will happen if you uncomment this line and comment the //next line //char ch; int fileSize=-1; fd = fopen(argv[1], "r"); do{ ch=getc(fd); //0xFF fileSize++; printf("fileSize=%d\n", fileSize); printf("Char read is ch=%c, in hex ch=%#hhx EOF is %#x\n\n", ch, ch, EOF); sleep(1); } while( ch != EOF); //ch =0x FF, EOF=0x FFFF FFFF printf(" \nout of do while loop now.\n\n"); printf("ch=%d EOF=%#x\n", ch, EOF); printf("size of char =%ld size of EOF=%ld\n", sizeof(char), sizeof(EOF)); printf("Size of %s is %d\n", argv[1], fileSize); } //suggeson: levae all the printf statment in place //run the code to observe the output //then use gdb to find out the "bug"
//filesize1v.c
#include
#include
int main(int argc, char *argv[]){
FILE *fd;
//unsigned char ch; //what will happen if you uncomment this line and comment the //next line
char ch;
int fileSize=-1;
fd = fopen(argv[1], "r");
do{
ch=getc(fd); //0xFF
fileSize++;
printf("fileSize=%d\n", fileSize);
printf("Char read is ch=%c, in hex ch=%#hhx EOF is %#x\n\n", ch, ch, EOF);
sleep(1);
} while( ch != EOF); //ch =0x FF, EOF=0x FFFF FFFF
printf(" \nout of do while loop now.\n\n");
printf("ch=%d EOF=%#x\n", ch, EOF);
printf("size of char =%ld size of EOF=%ld\n", sizeof(char), sizeof(EOF));
printf("Size of %s is %d\n", argv[1], fileSize);
}
//suggeson: levae all the printf statment in place
//run the code to observe the output
//then use gdb to find out the "bug"
You are getting this error and stuck on the do/while loop becuase in the code we are using the unsigned char and the EOF is a signed int quantity , so these value can never be equal in any case, so the code is goin in the infinite loop , you need to declare the ch as the int so that these values can be compared, so unsigned char ch , can only contain the number or the magnitude without any sign in front and the EOF is defined as -1 in the stdio.h and the other programming langugaes as well , so , the values when compared will always give True as a result because they are not eqaul , so declare the ch as signed int.