C Program to count the no of characters,words,lines using Files...

#include<stdio.h>

void main()
{
    FILE *f;
    f=fopen("string.txt","w");
    char a[100];
    printf("Enter any text followed by ~");
    scanf("%[^~]s",a);
    // Writing to a text file...
    fprintf(f,"%s",a);
    fclose(f);

    // Counting the no of characters..
    char t;
    f=fopen("string.txt","r");
    int c=0;
    while(!feof(f)){
            t=fgetc(f);
            if(t!=' ' && t!='\n'){
                c++;
            }
    }
    printf("\nThe number of characters in the given text is..%d",c-1);
    // Counting the no of lines...
    rewind(f);
    c=0;
    while(!feof(f)){
        t=fgetc(f);
        if(t=='\n'){
            c++;
        }
    }
    printf("\nThe number of lines in the given text..%d",c+1);
    // Counting the no of words..
    rewind(f);
    c=0;
    char t1,t2;
    t1=fgetc(f);
    t2=fgetc(f);
    while(!feof(f)){
        if((t1!=' ' && t1!='\n')&&(t2==' '|| t2=='\n')){
            c++;
        }
        t1=t2;
        t2=fgetc(f);

    }
    printf("\nThe number of words in the given text..%d",c+1);
    fclose(f);
}

No comments:

Post a comment