0

I wrote a program in C to count lines in a txt file but it fails in some cases.

For example:

File1.txt- "Helloworld" - 0 lines

File2.txt- "Helloworld "- 1 line

My guess is that it happens because it cannot find the '\n' character at the end in the File1.txt file. Here is my code:

int main()
{
    
    FILE *fp1;

    int count_lines = 0;

    printf("Enter file name: ");

    scanf("%s", filename);

    sprintf(finalname, "%s.txt", filename);

    fp1 = fopen(finalname, "r");

    char chr = fgetc(fp1);

    while (chr != EOF)
    {
        
        if (chr == '\n')
        {
            count_lines = count_lines + 1;
        }
        
        chr = fgetc(fp1);
    }
    
    fclose(fp1);

    printf("There are %d lines in %s\n", count_lines, finalname);

    return 0;
}

Any help would be appreciated.

vmp
  • 2,370
  • 1
  • 13
  • 17
  • you may use fgets or getline instead . – Ken Lee Jan 26 '21 at 01:14
  • When you have a fairly common issue, please search for an existing answer (there are about 50 by my count) before asking a question. That will help ensure this site does not become fragmented with numerous questions surrounding the same topic. If for some reason you question is new or different, the post the link for the existing question and explain how your question is different. Each of the foregoing answers discuss handling non-POSIX end-of-file. – David C. Rankin Jan 26 '21 at 01:20

1 Answers1

0

That is because you might not have a \n after the content in last line.

You could use another variable to save the previous char you had and if you reach EOF without a \n before it you increment the number of lines.

char chr = fgetc(fp1);
char prev;
while (chr != EOF)
{
    
    if (chr == '\n')
    {
        count_lines = count_lines + 1;
    }
    prev = chr;
    chr = fgetc(fp1);
}
if(prev != '\n')
   count_lines++;
vmp
  • 2,370
  • 1
  • 13
  • 17