Q:

C Program to Count Number of Words in a given file

0

C Program to Count Number of Words in a given file

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this example code, I am creating a text file “Info.txt” and writing into the string “Welcome to aticleworld”. When the file has been created successfully then open the file in reading mode and read all the string which has been written into the file at the time of the file creation.

Store all the read data into the buffer and use the function (wordCounter) to count the number of words.

#include <stdio.h>
#include <string.h>
#define TRUE   0
#define FALSE  1
//create file and write data
int createFile(char *pFileData)
{
    FILE *fpInfo = NULL;
    int len = 0;
    fpInfo = fopen("Info.txt", "w");//create file in write mode
    if(fpInfo== NULL)
        return 1;
    len = strlen(pFileData);
    fwrite(pFileData, 1, (len+1), fpInfo);//write data into the file
    fclose(fpInfo);//close the file
    fpInfo = NULL;
    return 0;
}
//read file data
int readFileData(char *pReadFileData)
{
    FILE *fpInfo = NULL;
    int len = 0;
    int data = 0;
    fpInfo = fopen("Info.txt", "r"); //open file in read mode
    if(fpInfo== NULL)
        return 1;
    while ((data = getc(fpInfo)) != EOF)//read file data till EOF
    {
        *pReadFileData++ = data;
    }
    fclose(fpInfo);//close the file
    fpInfo = NULL;
    return 0;
}
//count the word
unsigned wordCounter(char *PString)
{
    int flag = TRUE;
    unsigned int wCounter = 0; // word counter
    // Runt untill not get null
    while (*PString)
    {
        //Set the flag true if you got the space
        if (*PString == ' ')
        {
            flag = TRUE;
        }
        else if (flag == TRUE) //if next word is not empty and flag is true,
        {
            //increment word counter
            flag = FALSE;
            ++wCounter;
        }
        // Move to next character
        ++PString;
    }
    return wCounter;
}
int main(int argc, char *argv[])
{
    char *pMsg = "Welcome to aticleworld"; //Msg
    int status = 0;
    char fileData[256] = {0};
    unsigned int count = 0;
    status = createFile(pMsg); //create the file and write string
    if(status== 1)
        return 1;
    status = readFileData(fileData); //read file data
    if(status== 1)
        return 1;
    printf("Data Read from file : %s\n",fileData);
    count = wordCounter(fileData); //count words
    printf("No of words : %u\n",count);
    return 0;
}

Output:

Data Read from file : Welcome to aticleworld
No of words : 3

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< C Program to Count Number of Words in a given stri...