- This topic has 2 replies, 3 voices, and was last updated 14 years, 9 months ago by .
Viewing 2 reply threads
Viewing 2 reply threads
- The forum ‘C Programming’ is closed to new topics and replies.
Home › Forums › C Programming › How to count characters from text file
How to count characters from text file ….counting number of character occured from a file(txt)..line by line
please
If you just want to count all the characters , you can do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include<stdio.h><br /> #include <string.h><br /> int main(void)<br /> {<br /> // open a text file for reading<br /> FILE * in_file;<br /> in_file = fopen("c:\programs\help\text1.txt","r");<br /> <br /> <br /> if ( ! in_file )<br /> {<br /> printf ( "file did not openn" );<br /> return 1;<br /> }<br /> int numberOfCharacters = 0;<br /> char ch = fgetc ( in_file );<br /> while ( ch != EOF )<br /> {<br /> numberOfCharacters ++;<br /> ch = fgetc ( in_file );<br /> }<br /> printf ( "nthe number of characters is " );<br /> printf ( "%i" , numberOfCharacters );<br /> fclose ( in_file );<br /> return 0;<br /> } |
Count each line, voila: (you can pass the filename/path as the first argument)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include <stdio.h><br /> <br /> int main(int argc,char **argv)<br /> {<br /> const int max=1024;<br /> int r=0,count=0,i;<br /> FILE *f;<br /> char buff[max+3];<br /> <br /> if (argc==2)<br /> {<br /> if ((f=fopen(argv[1],"rb"))==NULL)<br /> {<br /> r=2;<br /> printf("cannot open file!n");<br /> }<br /> else<br /> {<br /> while (!feof(f))<br /> {<br /> buff[0]=0;<br /> fgets(buff,max,f);<br /> count++;<br /> <br /> for (i=0;i<max && buff!=0 && buff!='r' && buff!='n';i++);<br></max> <br /> printf("Line %i, count %in",count,i);<br /> }<br /> <br /> fclose(f);<br /> }<br /> }<br /> else<br /> {<br /> r=1;<br /> printf("usage: count <file>n");<br /> }<br /> <br /> return r;<br /> }</file> |