Counting Characters, Spaces and Lines in a C File

Character-by-character file reading can be used to count spaces, line breaks or other characters. Store the return value of fgetc() in an int so that EOF can be detected correctly.

Count Line Breaks and Spaces Top ↑

#include <stdio.h>

int main(void) {
    FILE *file = fopen("data2.txt", "r");

    if (file == NULL) {
        perror("data2.txt");
        return 1;
    }

    int ch;
    unsigned long line_breaks = 0;
    unsigned long spaces = 0;

    while ((ch = fgetc(file)) != EOF) {
        if (ch == '\n') {
            line_breaks++;
        }

        if (ch == ' ') {
            spaces++;
        }
    }

    if (ferror(file)) {
        printf("An error occurred while reading the file.\n");
        fclose(file);
        return 1;
    }

    fclose(file);

    printf("Line breaks: %lu\n", line_breaks);
    printf("Spaces: %lu\n", spaces);

    return 0;
}

Example Input File Top ↑

welcome to plus2net
Next Line

Count Any Chosen Character Top ↑

Key change: compare every byte with the character you want to count.

#include <stdio.h>

int main(void) {
    FILE *file = fopen("data2.txt", "r");
    const int target = 'e';
    unsigned long count = 0;

    if (file == NULL) {
        perror("data2.txt");
        return 1;
    }

    int ch;

    while ((ch = fgetc(file)) != EOF) {
        if (ch == target) {
            count++;
        }
    }

    fclose(file);

    printf("Occurrences of '%c': %lu\n", target, count);
    return 0;
}

Why the Old char + EOF Pattern Is Unsafe Top ↑

The earlier page stored the file character in char and tested that variable against EOF. That can fail because EOF is an int value outside the range needed for ordinary unsigned byte values. Use:

int ch;

while ((ch = fgetc(file)) != EOF) {
    /* process ch */
}

Related File Tutorials Top ↑





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer