Loading...

C essentialsProject

Final project: build a command-line application

60 min lesson

Next
  • The final project brings together everything you have learned: a small command-line application that reads a text file, counts words, and prints a summary.
  • Building a real program matters because it turns separate lessons into one working skill you can show and extend.
  • Think of the project as a small kitchen: the recipe (the plan) uses many tools (functions, files, memory, error handling) to produce one dish (a word count report).
  • The program reads a file name from argv[1], opens it with fopen, reads lines with fgets, and splits each line into words.
  • Word counting means skipping spaces and counting transitions from non-letter to letter, using ctype functions like isspace and isalpha.
  • Memory and error handling: check fopen and argv, free any heap memory, and return nonzero exit codes on failure.
  • The computer reads the file through a buffer, updates counters for words, lines and characters, and prints the totals.
  • The syntax brings together: int main(int argc, char *argv[]), fopen, fgets, strtok or manual scanning, and printf.
  • A realistic use: a small wc-like tool you can run on any text file to count lines, words and characters.
  • A surprising detail: strtok modifies the string it scans, so if you need the original line, copy it first.
  • The example program counts lines, words and characters in a fixed in-memory string, using the same logic you would use on a file.
Keep in mind
  • Plan the program first: inputs, outputs, error cases and the main loop.
  • Check every fopen, argv access and allocation; report errors clearly.
  • Count with clear rules (whitespace separates words) so results are predictable.
  • Test with different inputs, including empty files and very long lines.
  • You built a real command-line tool. Be proud of what you have learned!
main.c
#include <stdio.h>
#include <ctype.h>

// Count lines, words and characters in a string
void countText(const char *text, int *lines, int *words, int *chars) {
    int inWord = 0;
    *lines = 0; *words = 0; *chars = 0;
    for (const char *p = text; *p != '\0'; p++) {
        // Every character counts toward the total
        (*chars)++;
        // A newline ends a line
        if (*p == '\n') {
            (*lines)++;
        }
        // Whitespace ends the current word
        if (isspace((unsigned char)*p)) {
            inWord = 0;
        } else if (!inWord) {
            // Transition from whitespace to a word
            inWord = 1;
            (*words)++;
        }
    }
    // Count a final line if the text does not end with a newline
    if (*chars > 0 && text[*chars - 1] != '\n') {
        (*lines)++;
    }
}

int main(void) {
    // Sample text that would normally come from a file
    const char *text = "hello world\nthis is C\n";
    int lines = 0, words = 0, chars = 0;

    // Count everything in one pass
    countText(text, &lines, &words, &chars);

    // Print the summary
    printf("Lines: %d\n", lines);
    printf("Words: %d\n", words);
    printf("Chars: %d\n", chars);
    return 0;
}

What happens: Lines: 2 Words: 5 Chars: 20

Breaking it down

countText signature

void countText(const char *text, int *lines, int *words, int *chars)

Takes the text and pointers to three counters. Pointers let the function update the caller's variables.

Character loop

for (const char *p = text; *p != '\0'; p++)

Walks the string one character at a time until the null terminator. This is the standard C string traversal.

Line count

if (*p == '\n') (*lines)++;

Each newline marks the end of a line. The final line is counted separately if it has no newline.

Word detection

if (isspace(...)) inWord = 0; else if (!inWord) { inWord = 1; (*words)++; }

A word starts when we move from whitespace to a non-whitespace character. This avoids counting every letter.

Summary print

printf("Words: %d\n", words);

Prints the totals with labels so the output is easy to read, like the wc tool.

Project pieces

PiecePurposeLesson used
argvRead file nameCommand-line arguments
fopen/fgetsRead the fileFile I/O
isspace/isalphaSplit wordsStandard library
PointersUpdate countersPointers
Error checksHandle failuresError handling
MakefileBuild the toolMake

A helpful analogy

The project is like a small kitchen where several cooks (functions) work together to make one dish (the report). One cook opens the fridge (fopen), another chops ingredients (splitting words), and another plates the dish (printf). Each has one clear job, and the recipe ties them together.

Nesting rules

  • 1.Check argc before using argv[1], and print a usage message if it is missing.
  • 2.Check fopen for NULL and report errors with perror before continuing.
  • 3.Close every file you open and free every heap block before returning.
  • 4.Decide the counting rules up front (what counts as a word) so results are predictable.

Common mistakes

Reading argv[1] without checking argc

Avoid

const char *path = argv[1]; // may crash

Use instead

if (argc < 2) { printf("usage: app file\n"); return 1; }

If the user passes no file name, argv[1] is out of bounds. Always check argc and print usage.

Counting words by counting spaces

Avoid

words = spaces + 1; // wrong on empty text

Use instead

count transitions from whitespace to non-whitespace

Multiple spaces or leading spaces break the simple rule. Count word starts with the inWord flag.

Forgetting to close the file

Avoid

FILE *f = fopen(...); // no fclose

Use instead

FILE *f = fopen(...); if (!f) { perror("fopen"); return 1; } // ... use f ... fclose(f);

Leaving files open leaks handles and may lose buffered data. Close every file you open.

Quick tips

  • •Start with a working single-file version, then split into modules and add a Makefile.
  • •Test with empty files, files without a final newline, and very long lines.
  • •Add options like -w or -l later to mimic wc's flags.
  • •Use the safe patterns from earlier lessons: bounded copies, NULL checks, clear exit codes.
  • •Once it works, extend it: count unique words with a hash table, or read from stdin.
Previous
Next