-1

I'm trying to read a newline character in a text file and thus count the number of lines in a text document

Content of .txt file:

My
Name
Is
John

Output of my code:

Nm
s
on
Line number is 1

My code:

    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>


    int main()
    {

         FILE* filepointer ;
          filepointer = fopen("C:\\Users\\Summer Work\\Let's C\\Comnsole\\TestFile.txt","rb+") ;

        int count = 0 ;
        int ch;
        printf("%c\n",ch) ;

          while ((ch = fgetc(filepointer)) != EOF)
          {
             printf("%c",ch) ;
             ch = fgetc(filepointer)  ;

            char dh = ch;
            if (dh == '\n')
            count++ ;
           }


         printf("\nLine number is %d",count) ;

         fclose(filepointer) ;
         getchar() ;
         return 0;
 }

Can somone please explain why this is happening?

Update : Fixed code

    #include <stdlib.h>
    #include <string.h>
#include <stdio.h>


int main()
{

   FILE* filepointer ;
filepointer = fopen("C:\\Users\\Summer Work\\Let's C\\Comnsole\\TestFile.txt","rb+") ;

int count = 0 ;
int ch;


while ((ch = fgetc(filepointer)) != EOF)
{
    printf("%c",ch) ;
    if (ch == '\n')
        count++ ;

}


printf("\nLine number is %d",count) ;

fclose(filepointer) ;
getchar() ;
return 0;

}

OUTPUT

My
Name
Is
John
Line Number is 3

Ambareesh S J
  • 97
  • 1
  • 9

1 Answers1

0

You are doing twice fgetc in while loop. Also you are copying ch to dh without any particular reason. I improved your code, tested it and it works flawless. There you go:

      while ((ch = fgetc(filepointer)) != EOF)
      {
        printf("%c",ch);
        if (ch == '\n')
           count++;
      }

Also you need to initialize int ch = 0;, because you print it before it gets any value which leads to undefined behavior.

Mirakurun
  • 4,859
  • 5
  • 16
  • 32