C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Find largest word in a file

A great example for your File Handling + String Processing.

C Program: Find largest word in a file

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

 

int main() {

    FILE *file;

    char filename[100];

    char word[100], largest[100] = "";

    int maxLen = 0;

 

    // Step 1: Get the filename from user

    printf("Enter file name: ");

    scanf("%s", filename);

 

    // Step 2: Open the file

    file = fopen(filename, "r");

    if (file == NULL) {

        printf("Unable to open file!\n");

        return 0;

    }

 

    // Step 3: Read each word and check its length

    while (fscanf(file, "%s", word) != EOF) {

        // Remove punctuation if any

        int len = strlen(word);

        while (len > 0 && ispunct(word[len - 1])) {

            word[len - 1] = '\0';

            len--;

        }

 

        if (len > maxLen) {

            maxLen = len;

            strcpy(largest, word);

        }

    }

 

    fclose(file);

 

    // Step 4: Display result

    if (maxLen > 0)

        printf("The largest word is: '%s' (Length: %d)\n", largest, maxLen);

    else

        printf("No words found in file.\n");

 

    return 0;

}

Output

 
Input File (sample.txt):

C programming language is exceptionally powerful and flexible.


OUTPUT :

The largest word is: 'exceptionally' (Length: 13)

Explanation

Step

Description

1

Prompts the user to enter a filename.

2

Opens the file in read mode.

3

Reads each word using fscanf().

4

Removes punctuation marks (like , . ! ?).

5

Compares word lengths and stores the longest one.

6

Prints the largest word and its length.