C Program to count the Number of Characters in a File

Counting the number of characters is important because almost all the text boxes that rely on user input have certain limitations on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is 80 per post for Snapchat.

Determining character limits become crucial when the tweet and Facebook post updates are being done through API’s.

Note: This program would not run on online compilers. Please make a text (.txt) file on your system and give its path to run this program on your system.

Approach: The characters can be counted easily by reading the characters in the file using getc() method. For each character read from the file, increment the counter by one.

Below is the implementation of the above approach:

Program:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C Program to count
// the Number of Characters in a Text File
  
#include <stdio.h>
#define MAX_FILE_NAME 100
  
int main()
{
    FILE* fp;
  
    // Character counter (result)
    int count = 0;
  
    char filename[MAX_FILE_NAME];
  
    // To store a character read from file
    char c;
  
    // Get file name from user.
    // The file should be either in current folder
    // or complete path should be provided
    printf("Enter file name: ");
    scanf("%s", filename);
  
    // Open the file
    fp = fopen(filename, "r");
  
    // Check if file exists
    if (fp == NULL) {
        printf("Could not open file %s",
               filename);
        return 0;
    }
  
    // Extract characters from file
    // and store in character c
    for (c = getc(fp); c != EOF; c = getc(fp))
  
        // Increment count for this character
        count = count + 1;
  
    // Close the file
    fclose(fp);
  
    // Print the count of characters
    printf("The file %s has %d characters\n ",
           filename, count);
  
    return 0;
}

chevron_right


Output:

Note: The text file used to run this code can be downloaded from here



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.