Linux Programming – Part 14: Programm Cat Command Ⅱ

Cat command… again!

Here’s an updated version of the original cat command from last year.

While I previously authored the original code for the “Linux Programming – Part 11: Program Cat Command” last year, I have now taken the time to refine it further and present an updated version.

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[]) {
    int i;
    for (i = 1; i< argc; i++) {
        FILE *f;
        int c;

        f = fopen(argv[i], "r");
        if (!f) {
            perror(argv[i]);
            exit(1);
        }
       while ((c = fgetc(f)) != EOF) {
            if (putchar(c) < 0) exit(1);
        }
        fclose(f);
    }
    exit(0);
}

Description:

And here is what it does:

This is a simple program that reads one or more files specified as command-line arguments and writes their contents to the standard output.

The program starts by iterating over each command-line argument starting from index 1 (index 0 is the name of the program itself). For each argument, it opens the file using fopen() and reads the contents character-by-character using fgetc() until the end of file (EOF) is reached. The characters are then printed to the standard output using putchar().

If an error occurs while opening the file or writing to the standard output, the program prints an error message and exits with a non-zero status. Otherwise, it exits with a zero status indicating success.

Leave a Reply