/* mycopy: copies its first command-line argument file to the second. */ /* This is Listing 17-4 in the text. */ #include #include FILE * file_open(char name[], char access_mode[]); int fcopy(FILE *inf, FILE *outf); main(int argc, char *argv[]) { FILE *inf, *outf; if (argc!=3) { /* Check command line */ printf("You must supply source and destination filenames.\n"); exit(EXIT_FAILURE); } inf = file_open(argv[1], "rb"); /* Try to open files */ outf = file_open(argv[2], "wb"); if (fcopy(inf, outf) != 0) { /* Copy file */ perror("Error writing file"); /* Error message on failure */ fclose(inf); fclose(outf); exit(EXIT_FAILURE); } fclose(inf); fclose(outf); return 0; } /***** fcopy: copies a file ****** On entry: inf is open for binary input, outf for binary output. On exit: Remaining data in inf is copied to outf; both files still open. Returns 0 for success, 1 for error transferring data. */ #define BUFMAX (4096) int fcopy(FILE *inf, FILE *outf) { char buffer[BUFMAX]; size_t num_read, num_written; while ( num_read = fread(buffer, 1, BUFMAX, inf), /* ^ Note: chars always have size 1 */ num_read > 0 /* The final block may be shorter than BUFMAX */ ) { num_written = fwrite(buffer, 1, num_read, outf); if (num_written != num_read) { return 1; /* failure */ } } if (ferror(inf)) { return 1; } return 0; /* success */ } /* The following #ifdef includes the file_open function; if you have it in a personal function library, you may wish to delete these lines and link the two files separately. */ #ifdef __cplusplus #include "lst10-7.cpp" /* or maybe "lst10-7.cxx" */ #else #include "lst10-7.c" #endif