#include #include int copy_char_by_char(FILE * input, FILE * output) { for (int c = fgetc(input); c != EOF; c = fgetc(input)) if (fputc(c, output) == EOF){ fprintf(stderr, "could not write into output file\n"); return 0; } return 1; } int copy_with_buffer(FILE * input, FILE * output) { char buffer[1024]; size_t s; while ((s = fread(buffer, sizeof(char), 1024, input)) > 0) { size_t w = 0; do { w += fwrite(buffer, sizeof(char), s - w, input); if (w == 0){ fprintf(stderr, "could not write into output file\n"); return 0; } } while (w < s); } return 0; } /* syntax: ./copy -c file1 file2 * * makes a copy of file1 into a new file file2 */ int main(int argc, char * argv[]) { FILE * input; FILE * output; int buffer; const char * input_fname; const char * output_fname; switch (argc) { case 1: case 2: fprintf(stderr, "usage: %s [b=] \n", argv[0]); return 1; case 3: input_fname = argv[1]; output_fname = argv[2]; buffer = 0; break; default: if (strcmp(argv[1], "-b") != 0) { fprintf(stderr, "usage: %s [-b] \n", argv[0]); return 1; } buffer = 1; input_fname = argv[2]; output_fname = argv[3]; } input = fopen(input_fname, "rb"); if (input == 0) { fprintf(stderr, "could not open file %s for reading\n", argv[1]); return 1; } output = fopen(output_fname, "wb"); if (output == 0) { fprintf(stderr, "could not open file %s for writing\n", argv[2]); fclose(input); return 1; } if (buffer) copy_with_buffer(input, output); else copy_char_by_char(input, output); fclose(input); fclose(output); }