C Programming - Input / Output - Discussion

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

int main()
{
    FILE *ptr;
    char i;
    ptr = fopen("myfile.c", "r");
    while((i=fgetc(ptr))!=NULL)
        printf("%c", i);
    return 0;
}
Print the contents of file "myfile.c"
Print the contents of file "myfile.c" upto NULL character
Infinite loop
Error in program
Answer: Option
Explanation:
The program will generate infinite loop. When an EOF is encountered fgetc() returns EOF. Instead of checking the condition for EOF we have checked it for NULL. so the program will generate infinite loop.
Discussion:
13 comments Page 1 of 2.

François said:   1 decade ago
Well B is the right answer for me on Linux gcc.

Bhandari said:   1 decade ago
According to me output depends upon the contents of file if it encounters null character than it will terminate else there will be infinite loop.

Niyati said:   1 decade ago
We are opening file in read mode then how is it possible to access the file contents(printing the contents of this file)?

Kiran said:   1 decade ago
@Niyati.

Here we are accessing file from read mode ("r").
So the value accessed is printing on the screen, not into the file.
If you want to print (write) into the file then you should open in "w" mode.

Cherry said:   1 decade ago
It depends upon contents of the file.

If the file contains NULL.

Then the o/p is.

Print the contents of file "myfile.c" up to NULL character.

Otherwise infinite loop.

Zahir said:   1 decade ago
What if the file has a NULL character in it? Then the correct answer would be option B. The content of the file should be displayed with the question.

Akanchha said:   1 decade ago
When is null used and when is EOF?

Sasuke said:   1 decade ago
Its coming segmentation fault for me.

Compilation:
temp.c: In function \'main\':
temp.c:8:25: warning: comparison between pointer and integer [enabled by default]
while((i=fgetc(ptr))!=NULL)

Running:
Segmentation fault (core dumped)

GAMI NIPULKUMAR K. said:   1 decade ago
fgetc returns EOF.
fgets returns NULL.

At the end of file, otherwise nonzero value.

Divya said:   8 years ago
On failure file returns EOF so, here we are checking up to NULL, so, up to NULL, it will take. Because after that no content will be there in a file for checking.

Correct me, If I am Wrong.


Post your comments here:

Your comments will be displayed after verification.