Home › Forums › C Programming › How to count characters from text file
- This topic has 2 replies, 3 voices, and was last updated 16 years, 7 months ago by Priyansh Agrawal.
Viewing 2 reply threads
- AuthorPosts
- April 3, 2008 at 3:35 am #2088rahul bansalParticipant
How to count characters from text file ….counting number of character occured from a file(txt)..line by line
please
- April 3, 2008 at 1:14 pm #3373HumayanParticipant
If you just want to count all the characters , you can do:
1234567891011121314151617181920212223242526#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 />} - April 28, 2008 at 9:32 am #3374Priyansh AgrawalParticipant
Count each line, voila: (you can pass the filename/path as the first argument)
12345678910111213141516171819202122232425262728293031323334353637383940#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>
- AuthorPosts
Viewing 2 reply threads
- The forum ‘C Programming’ is closed to new topics and replies.