C Programming - Input / Output - Discussion


What will be the output of the program ?


int main()
    FILE *fp;
    unsigned char ch;
     /* file 'abc.c' contains "This is IndiaBIX " */
    fp=fopen("abc.c", "r");
    if(fp == NULL)
        printf("Unable to open file");
    while((ch=getc(fp)) != EOF)
        printf("%c", ch);

    printf("\n", ch);
    return 0;

[A]. This is IndiaBIX
[B]. This is
[C]. Infinite loop
[D]. Error

Answer: Option C


The macro EOF means -1.

while((ch=getc(fp)) != EOF) Here getc function read the character and convert it to an integer value and store it in the variable ch, but it is declared as an unsigned char. So the while loop runs infinitely.

Dev And Ankit said: (Aug 22, 2012)  
We can see that char ch is unsigned...so, it can take only positive values..so when fp reaches to EOF ie, -1....it is converted into garbage value which is positive...
so, the loop will run infinte times..bcoz, the condition (ch=getc(fp)!=EOF) is always satisfied...

Bhargav said: (Sep 2, 2012)  
What if value of ch is 0 (zero) ?

Ashok said: (May 23, 2013)  
If value of of ch=0; then condition Satisfies(ch=getc(fp)!=EOF) Hence loop continues to run.

Anurag said: (Aug 10, 2013)  
There's no counter to increase the value of 'fp' in the while, hence it ends up in an infinite loop.

Moreover, since its an unsigned char, hence that's another reason for the program to end up in an infinite loop.

Praveen said: (Mar 31, 2016)  
How 'getc' gets the character from the file, fgetc() should be used to access the char from the file?

Is that possible?

Stephen said: (May 19, 2016)  
I'm also having the same doubt @Praveen.

Please can anyone help me?

Khan said: (Jun 5, 2016)  
Thank you @Dev And Ankit.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.