In: Computer Science
here it is running nonstop. so here one thing should be wrong. your task is solving that problem #include <stdio.h> #include<unistd.h> 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"
Thre reason it is running infinitely is because you are reading the file using unsigned char ch . So what happens is that at the end of while loop, it checks for EOF but EOF is a signed value. Now you are comparing signed value with unsigned value. So the condition will always result in true and while lioop will loop continuously. One other reason can be the implementation of compiler. Sometimes compilers have definition of EOF as -1 . Now again the problem of signed and unsigned comparing will occur and loop will always result in true condition. To avoid this ,use char ch instead of unsigned char ch. When you will use char ch, it will not loop infinitely.
Below is the the code of same program in Windows. In windows sleep() method is Written as Sleep() [capital S] . And we need to include <windows.h> other than this the code is completely same. If you are not using windows then dont include these differences. Just comment the line unsigned char ch and uncomment char ch. now run the program and it will work fine.
Windows Environment program with output:-->>
#include <stdio.h>
#include<windows.h>
#include<unistd.h>
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);
}
OUTPUT:
Look at console there is no infinite loop.