Programming example - cat

/*
 * Implementation of Unix cat command
 */
#include <stdio.h>

void
copy_file_to_stdout(FILE *f) {
    while (1) {
        int ch = fgetc(f);
        if (ch == EOF)
             break;
        if (putchar(ch) == EOF) {
            fprintf(stderr, "cat:");
            perror("");
            exit(1);
        }
    }
}

int
main(int argc, char *argv[]) {
    FILE *f;
    int i;
    
    if (argc == 1) {
        copy_file_to_stdout(stdin);
        return 0;
    }
    
    for (i = 1; i < argc; i++) {
        f = fopen(argv[i], "r");
        if (f == NULL) {
            fprintf(stderr, "cat: %s: ", argv[i]);
            perror("");
            continue;
        }
        copy_file_to_stdout(f);
        fclose(f);
    }
    return 0;
}

Index