How to count words in a text file in C

In this article, we are going to learn How to count words in a text file in C.We will read each word from the text file in each iteration and increment a counter to count words.

C fscanf function


The scanf function is available in the C library. This function is used to read formatted input from a stream. The syntax of fscanf function is:

Syntax

int fscanf(FILE *stream, const char *format, …)

Parameters

  • stream − This is the pointer to a FILE object that identifies the stream.
  • format − This is the C string that contains one or more of the following items − Whitespace character, Non-whitespace character, and Format specifiers. A format specifier will be as [=%[*][width][modifiers]type=].

How to count words in a text file in C using fscanf


In this c program, we are making use of the fscanf function to read the text file. The first thing we are going to do is open the file in reading mode. So using open() function and “r” read mode we opened the file.

  • The next step is to find the file stats like what is the size of the data this file contains. so we can allocate exact memory for the buffer that is going to hold the content of this file. We are using the stat() function to find the file size.
  • Once we have the size and buffer allocated for this size, we start reading the file by using the fscanf() function.
  • We keep reading the file word by word until we reach the end of file.In fscanf function, we are passing “%39[^-\n] as the argument so we can read the text until we find the next word. The code will look like:
fscanf(in_file, "%39[^-\n]", file_contents)
  • We are maintaining a variable to count the number of words in the file. On each word count, we increment the counter.

C Program to count words in a text file in C


To run this program, we need one text file with the name Readme.txt in the same folder where we have our code.The content of the file is:

Hello My name is 
John 
danny
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

const char* filename = "Readme.txt";

int main(int argc, char *argv[])
{
	int wordcount = 0;
    FILE *in_file = fopen(filename, "r");
    if (!in_file) 
	{
        perror("fopen");
        return 0;
    }

    struct stat sb;
    if (stat(filename, &sb) == -1) 
	{
        perror("stat");
        return 0;
    }

    char *file_contents = malloc(sb.st_size);

    while (fscanf(in_file, "%[^-\n ] ", file_contents) != EOF) 
	{
		wordcount++;
        printf("%s\n", file_contents);
    }
	

	printf("The file have total words = %d\n",wordcount);
	
    fclose(in_file);
    return 0;
}

Output

Hello
My
name
is
John
danny
The file have total words = 6