Home Forums C Programming How to count characters from text file

Viewing 2 reply threads
  • Author
    Posts
    • #2088
      rahul bansal
      Participant

      How to count characters from text file ….counting number of character occured from a file(txt)..line by line

      please

    • #3373
      Humayan
      Participant

      If you just want to count all the characters , you can do:
       

      #include
      #include
      int main(void)
      {
       // open a text file for reading
       FILE * in_file;
       in_file = fopen("c:\programs\help\text1.txt","r");
       

       if ( ! in_file  )
       {
        printf ( "file did not openn" );
        return 1;
       }
          int numberOfCharacters = 0;
       char ch = fgetc ( in_file );
       while ( ch != EOF )
       {
              numberOfCharacters ++;
              ch = fgetc ( in_file );
       }
       printf ( "nthe number of characters is " );
       printf ( "%i" , numberOfCharacters );
       fclose ( in_file );
          return 0;
      }
    • #3374
      Priyansh Agrawal
      Participant

      Count each line, voila: (you can pass the filename/path as the first argument)

      #include 

      int main(int argc,char **argv)
      {
      const int max=1024;
      int r=0,count=0,i;
      FILE *f;
      char buff[max+3];

      if (argc==2)
      {
      if ((f=fopen(argv[1],"rb"))==NULL)
      {
      r=2;
      printf("cannot open file!n");
      }
      else
      {
      while (!feof(f))
      {
      buff[0]=0;
      fgets(buff,max,f);
      count++;

      for (i=0;i
      printf("Line %i, count %in",count,i);
      }

      fclose(f);
      }
      }
      else
      {
      r=1;
      printf("usage: count n");
      }

      return r;
      }
Viewing 2 reply threads
  • The forum ‘C Programming’ is closed to new topics and replies.