Cottimizzazionealgoritmiprogrammazione

Algorithmic improvement in C: counting characters with fgetc()

How to think about optimizing C code, delegating computations to low-level languages and improving performance. First exercise: count lowercase 'a' and total characters from a file.

Published May 14, 20262 min readYouTube video
Algorithmic improvement in C: counting characters with fgetc()

New series: algorithmic improvement in C. Not a C course, mind you. A way to practice thinking better about code.

Why? Because when a project grows and the server starts sweating, you end up with badly written software to fix. And then you need to know how to:

  • use resources without wasting them;
  • not fry the CPU;
  • move heavy computation to a low-level language, leaving the rest to the high-level one.

The first exercise

A text file, whose name is requested from the user, contains arbitrary characters. Write a C89 program that:

  • counts how many lowercase 'a' letters there are
  • counts how many characters there are in total
  • displays both results. Use fgetc().

Before writing code, the flow:

  1. ask for the file name;
  2. open it for reading; if it doesn't exist, error and out;
  3. read one character at a time until EOF;
  4. if it's 'a' → count_a++; if it's not '\n' → count_total++;
  5. print, close, done.

The code

Here it is:

/* QUESTION 1. (6 points) A text file, whose name is requested from the user, contains arbitrary characters. Write a C89 program that: - counts how many lowercase letters 'a' are present - counts how many total characters are present - displays both results. Use fgetc(). */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 20 int main(){ char nome_file[MAX]; printf("Enter filename: "); scanf("%s", nome_file); FILE *fp; fp = fopen(nome_file, "r"); if(!fp){ return EXIT_FAILURE; } int ch, count_a = 0, count_total = 0; while ( (ch = fgetc(fp)) != EOF ){ if(ch == 'a'){ count_a = count_a + 1; } if (ch != '\n'){ count_total++; } } printf("Total lowercase 'a': %d\n", count_a); printf("Total characters (excluding newlines): %d", count_total); fclose(fp); return EXIT_SUCCESS; }

Why exclude `\n`?

Usually "total characters" means the visible ones, without line breaks.

In the video my count didn't match an AI's. The file had 388 characters excluding newlines: after adding the ch != '\n' check, the program gave the same number. Without that filter, line breaks inflate the total.

What a dumb exercise teaches

Dumb up to a point:

  • one loop: you read the file once, not twice;
  • drop what you don't need right away, without storing it;
  • handle the error if the file isn't there (EXIT_FAILURE);
  • C89 means C89: declarations at the top of the block, no // comments.

The point of the series: don't write everything in C. Use C only where the bottleneck is, and leave the rest to Python or JavaScript.

Next episode: memory, pointers and sorting algorithms.