Skip to content
Laviyx Learn

Try

PPS Lab · Experiment 30

Count a character in a file using command-line arguments

CFilesJNTUH R22 · CS108ES

Aim

To write a C program that counts how many times a character occurs in a text file, where the file name and the character are given as command-line arguments.

Algorithm

  1. Check that exactly two arguments were given: the file name and the character. If not, print how to use the program and stop.
  2. Take the character to count from the first letter of the second argument.
  3. Open the file for reading. If it cannot be opened, print an error and stop.
  4. Read the file one character at a time with fgetc until it returns EOF. Add 1 to a counter each time the character matches.
  5. Close the file and print the count.

Program

C
#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <file name> <character>\n", argv[0]);
        return 1;
    }

    char target = argv[2][0];
    FILE *fp = fopen(argv[1], "r");
    if (fp == NULL) {
        printf("Cannot open file %s\n", argv[1]);
        return 1;
    }

    int ch, count = 0;
    while ((ch = fgetc(fp)) != EOF) {
        if (ch == target) {
            count++;
        }
    }
    fclose(fp);

    printf("'%c' occurs %d times in %s\n", target, count, argv[1]);
    return 0;
}

Output

Input file: notes.txt (Text)
Every experiment needs an aim.
Write the program, then the output.
Keep the record neat.
Output
$ ./a.out notes.txt e
'e' occurs 15 times in notes.txt

Recorded by compiling and running this exact program.

How it works

argc is the number of command-line words, including the program name, so ./a.out notes.txt e gives argc = 3, argv[1] = "notes.txt" and argv[2] = "e".

The count is case-sensitive: 'e' and 'E' are different characters. To ignore case, compare tolower(ch) with tolower(target) from ctype.h.

Common mistakes

  • Storing the result of fgetc in a char. fgetc returns an int so that EOF (usually −1) can be told apart from every real character. Use int ch.

  • Not checking whether fopen returned NULL. Reading from a file that failed to open crashes the program.

  • Using argv[2] (a string) where a character is needed. The character is argv[2][0].

  • Forgetting fclose. For a file opened only for reading this rarely shows a bug, but it is a habit to keep for files you write to.

Viva questions

Try to answer each one aloud before you open it.

  • What are argc and argv?

    argc (argument count) is the number of words on the command line, including the program name. argv (argument vector) is an array of strings holding those words, with argv[0] being the program name.

  • Why is the variable that holds fgetc's result an int and not a char?

    fgetc returns every possible character value and also the special value EOF. An int can hold all of them separately; a char cannot, so the loop might stop early or never stop.

  • What does fopen return if the file does not exist?

    It returns NULL. The program must check for NULL before reading.

  • What is the difference between the "r", "w" and "a" modes of fopen?

    "r" opens an existing file for reading. "w" creates a new file or empties an existing one for writing. "a" opens a file for writing at the end, keeping what is already there.

  • How would you make the count ignore upper and lower case?

    Convert both characters to the same case before comparing, for example tolower(ch) == tolower(target), using ctype.h.

Learn the concepts

All Programming for Problem Solving Lab experiments →