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.