Home › Forums › C Programming › How to count characters from text file › Reply To: How to count characters from text file
April 28, 2008 at 9:32 am
#3374
Participant
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> |