C Programming - Input / Output - Discussion

1. 

Which of the following statement is correct about the program?

#include<stdio.h>

int main()
{
    FILE *fp;
    char ch;
    int i=1;
    fp = fopen("myfile.c", "r");
    while((ch=getc(fp))!=EOF)
    {
        if(ch == '\n')
            i++;
    }
    fclose(fp);
    return 0;
}

[A]. The code counts number of characters in the file
[B]. The code counts number of words in the file
[C]. The code counts number of blank lines in the file
[D]. The code counts number of lines in the file

Answer: Option D

Explanation:

This program counts the number of lines in the file myfile.c by counting the character '\n' in that file.


Koushik said: (Jan 8, 2011)  
Any one know - How to find space between words in that file?

Bill Roberts said: (Sep 16, 2011)  
It appears that i++ is over one line below the if statement, if it is, than it counts the characters in the file, else it counts the number of newline characters. Newline characters are not always indicative of a line, on windows \r\n is a line where on *nix it is \n.

Hemendra said: (Jan 20, 2012)  
Any one explain the answer in detail.

Ram said: (Mar 9, 2012)  
Some explanations are well, but some more are not to be understood, will you explain shortly.

Mahi said: (Jun 11, 2012)  
Firstly we are opening the file fp using fp = fopen("myfile.c", "r");
This also reads the file("r")
Now whatever the value equated to ch is counted
And we know that '\n' indicates every new lines arrival
By keeping track of \n in the statements
If(ch == '\n')
i++;
It results in number of new lines accessed

Sindhika K said: (Aug 31, 2012)  
Really good explanation. Thank you. @mahi.

Rakhtar said: (Aug 25, 2017)  
How it counts the number of line, even if we see in while loop the condition will create an infinite loop?

Sunanda said: (Oct 4, 2017)  
Whenever it will encounter \n i.e newline, it will increment the i value.That means it counts each and every line in the file.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.