Programming example - cp

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

void
copy_file_to_file(FILE *in, FILE *out) {
    while (1) {
        int ch = fgetc(in);
        if (ch == EOF)
             break;
        if (fputc(ch, out) == EOF) {
            fprintf(stderr, "cp:");
            perror("");
            exit(1);
        }
    }
}

int
main(int argc, char *argv[]) {
    FILE *in, *out;
    
    if (argc != 3) {
        fprintf(stderr, "cp  \n");
        return 1;
    }
    
    in = fopen(argv[1], "r");
    if (in == NULL) {
        fprintf(stderr, "cp: %s: ", argv[1]);
        perror("");
        return 1;
    }
    
    out = fopen(argv[2], "w");
    if (out == NULL) {
        fprintf(stderr, "cp: %s: ", argv[2]);
        perror("");
        return 1;
    }
    copy_file_to_file(in, out);
    fclose(in);  /* unnecessary as program is exiting */
    fclose(out); 
    return 0;
}

Index