poorvank
poorvank

Reputation: 7612

Number of lines in a file using c

I m new to File Handling in C.I am working on a program for counting the number of lines and characters in c.The program is working fine for characters but for lines the o/p is always one less.I have used new line characters for counting the no. of lines.Here is my code:

 main()
{
    FILE *fp;
    int c,nl=0,nc=0;
    char str[20];
    printf("Enter filename\n");
    scanf("%s",str);
    fp=fopen(str,"r");
    if(fp==NULL)
    {
        while(1)
        {
        printf("File does not exist\n");
        printf("Enter new filename\n");
        scanf("%s",str);
        fp=fopen(str,"r");
        if(fp!=NULL)
        break;
        }
    }
    c=getc(fp);
    while(c!=EOF)
    {
        if(c=='\n')
        nl++;
        nc++;
        c=getc(fp);
    }
    printf("no of lines=%d no of char=%d",nl,nc);
}

What is wrong with my implementation?.Is there any other method to count the no. of lines?

Upvotes: 3

Views: 6207

Answers (4)

varevarao
varevarao

Reputation: 2186

[Edited]

The final result will be 1 less because you're counting "\n" as the end-of-line, while the last line would not have "\n" as the end of line. It would just find no character. (Thanks for pointing out my error @Basile)

So for the correct answer just incremement the number of lines outside your while loop.

@DavidSchwartz finds this answer inadequate and pointing out the obvious. So for completeness I'll just add: (continued in the solution by David Schwartz).

Upvotes: 3

Raghu Srikanth Reddy
Raghu Srikanth Reddy

Reputation: 2711

The last line is not counted in your program as it is not encountering \n..

write the logic which also counts the last line..

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182865

It depends on your definition of a line. If a file contains only the single character 'a', does it have one line or no lines? By your program's logic, it has zero lines.

You could add, at the end of the while loop, outside the closing }, this line:

if (c != '\n') nl++;

That will add an extra line if the last character is not a newline. You should also initialize c to zero, otherwise this will cause unpredictable results if the file is empty.

As you can see from the other answers, it's not completely clear what it means to count the number of lines in a file. Make sure you have a very clear understanding of what it is precisely that you are trying to count before you start writing code.

Upvotes: 8

The last line of any file does not need to end with a newline \n character. Hence your program will report the number of newlines, not the number of "lines" (which is a conventionally defined concept).

Upvotes: 3

Related Questions