C Programming - Input / Output - Discussion

Discussion Forum : Input / Output - Find Output of Program (Q.No. 7)
7.
What will be the output of the program ?
#include<stdio.h>

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");
        exit(1);
    }
    while((ch=getc(fp)) != EOF)
        printf("%c", ch);

    fclose(fp);
    printf("\n", ch);
    return 0;
}
This is IndiaBIX
This is
Infinite loop
Error
Answer: Option
Explanation:

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.

Discussion:
7 comments Page 1 of 1.

Khan said:   9 years ago
Thank you @Dev And Ankit.

Stephen said:   9 years ago
I'm also having the same doubt @Praveen.

Please can anyone help me?
(1)

Praveen said:   9 years ago
How 'getc' gets the character from the file, fgetc() should be used to access the char from the file?

Is that possible?

Anurag said:   1 decade ago
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.

Ashok said:   1 decade ago
If value of of ch=0; then condition Satisfies(ch=getc(fp)!=EOF) Hence loop continues to run.

Bhargav said:   1 decade ago
What if value of ch is 0 (zero) ?

DEV and ANKIT said:   1 decade ago
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...
(2)

Post your comments here:

Your comments will be displayed after verification.