Counting Characters Words Lines In A File
In following program, a file pointer is created, which is initialized to point to file content, this pointer is used to loop through each character of file until end of file is reached. In the process we count each character, if a newline encounters then it is counted as line as well as character and word. Similarly if space or tab space encounters we count it as word and also as character.
Code
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main(int argc, char *argv[]){
FILE *f;
char ch;
int character=0, line=0,word=0;
f=fopen(argv[1],"r");
if(f==NULL){
printf("404: FILE NOT FOUND\n");
printf("HINT: PASS VALID FILENAME AS ARGUMENT TO THE PROGRAM\n");
fclose(f);
return 0;
}
printf("FILE NAME: %s\n",argv[1]);
while((ch=getc(f))!=EOF){
character++;
if(ch=='\n')
line++;
if(isspace(ch)||ch=='\t'||ch=='\n')
word++;
}
fclose(f);
putchar('\n');
printf("no of line=%d\n",line);
printf("no of word=%d\n",word);
printf("no of character=%d\n",character);
return 1;
}
-
Previous -
Next
This website is made possible by displaying online advertisements to our visitors.
Please consider supporting by disabling your ad blocker.
Please consider supporting by disabling your ad blocker.
loading comments...