C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Find smallest word in a file

C Program: Find smallest 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], smallest[100] = "";

    int minLen = 9999, len;

 

    // Step 1: Get the file name

    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 words one by one

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

        // Remove trailing punctuation

        len = strlen(word);

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

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

            len--;

        }

 

        // Ignore empty strings

        if (len == 0)

            continue;

 

        // Step 4: Check for smallest

        if (len < minLen) {

            minLen = len;

            strcpy(smallest, word);

        }

    }

 

    fclose(file);

 

    // Step 5: Display result

    if (minLen < 9999)

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

    else

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

 

    return 0;

}

Output

 
Input File  (data.txt):

C is a powerful general-purpose programming language.

OUTPUT :
The smallest word is: 'C' (Length: 1)

Explanation

Step

Description

1

Prompts user for file name

2

Opens the file in read mode

3

Reads each word with fscanf()

4

Removes punctuation (like , . ! ?)

5

Tracks the smallest (shortest) word

6

Displays the result