/* * stdc-file-copy.c - copy one file to a new location, possibly under a * different name. */ #include /* standard input/output routines. */ #define MAX_LINE_LEN 1000 /* maximal line length supported. */ /* * function: main. copy the given source file to the given target file. * input: path to source file and path to target file. * output: target file is being created with identical contents to * source file. */ int main(int argc, char* argv[]) { char* file_path_from; /* path to source file. */ char* file_path_to; /* path to target file. */ FILE* f_from; /* stream of source file. */ FILE* f_to; /* stream of target file. */ char buf[MAX_LINE_LEN+1]; /* input buffer. */ /* read command line arguments */ if (argc != 3 || !argv[1] || !argv[2]) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(1); } file_path_from = argv[1]; file_path_to = argv[2]; /* open the source and the target files. */ f_from = fopen(file_path_from, "r"); if (!f_from) { perror("Cannot open source file: "); exit(1); } f_to = fopen(file_path_to, "w+"); if (!f_to) { perror("Cannot open target file: "); exit(1); } /* copy source file to target file, line by line. */ while (fgets(buf, MAX_LINE_LEN+1, f_from)) { if (fputs(buf, f_to) == EOF) { /* error writing data */ perror("Error writing to target file: "); exit(1); } } if (!feof(f_from)) { /* fgets failed _not_ due to encountering EOF */ perror("Error reading from source file: "); exit(1); } /* close source and target file streams. */ if (fclose(f_from) == EOF) { perror("Error when closing source file: "); } if (fclose(f_to) == EOF) { perror("Error when closing target file: "); } return 0; }