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;
}
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.
Output: