/* File: filecopy.c * * An example that uses files and command line arguments. * Takes two filenames as command line arguments, and copies the contents * of the first file to the second. * * Because the '\n' and the '\0' are included in the strings returned by * fgets, any input line longer than 78 characters will be terminated. */ #include #define MAXLINE 80 /* max length of string */ int main(int argc, char *argv[]) { FILE *fpin, *fpout; /* pointers to in&out files */ char line[MAXLINE]; /* buffer to hold data */ if (argc < 3) /* must be 3 arguments - command */ { /* plus 2 filenames */ fprintf(stderr, "Usage: %s from_file to_file\n", argv[0]); return 0; } /* open the first file readonly */ if ((fpin = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "Error opening file %s\n", argv[1]); return 0; } /* open the 2nd file writeonly */ if ((fpout = fopen(argv[2], "w")) == NULL) { fprintf(stderr, "Error opening file %s\n", argv[2]); fclose(fpin); /* better close the 1st file */ return 0; } /* loop through the first file */ while (fgets(line, MAXLINE, fpin)) /* copying each line to the 2nd */ if (fputs(line, fpout) < 0) { fprintf(stderr, "Error writing to %s\n", argv[2]); break; } fclose(fpin); /* close the files */ fclose(fpout); return 0; }