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.

Rohan said:   7 years ago
FILE *ptr;

Step 1: A pointer ptr is created for FILE

char i;

Step 2: A variable i is declared as character...

ptr = fopen("myfile.c", "r");

Step 3: ptr is used to store the content of "myfile.c" which is opened in readable mode..

while((i=fgetc(ptr))!=NULL)
printf("%c", i);

Step 4: (i) while loop is used , when an EOF is encountered fgetc() returns EOF.
(ii) Instead of checking the condition for EOF we have checked it for NULL.


Ans ->> [c] infinite loop.

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)

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.

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.

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.

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)?

Onurag said:   8 years ago
If Null comes before some text and Eof I think It will execute upto Null.

"I Want to run" "I want" will get printed.

Utkarsh said:   6 years ago
What if actually have a NULL character in our file somewhere in between? Please tell me.


Post your comments here:

Your comments will be displayed after verification.