/* * Program that combines echo-test and copy-file: * * With no command-line arguments, echoes text from stdin to stdout. * * With two command-line arguments (infile and outfile), copies infile * to outfile. * * Otherwise prints error message. */ #include void copy_file(FILE * infile, FILE * outfile); int main(int argc, char *argv[]) { if (argc == 1) { fprintf(stderr, "enter text, control-D to end\n"); copy_file(stdin, stdout); } else if (argc == 3) { FILE * instream = fopen(argv[1], "r"); if (instream == NULL) { fprintf(stderr, "cannot open file %s\n", argv[1]); return 1; } FILE * outstream = fopen(argv[2], "w"); if (outstream == NULL) { fprintf(stderr, "cannot open file %s\n", argv[2]); return 1; } copy_file(instream, outstream); fclose(instream); fclose(outstream); } else { fprintf(stderr, "usage: %s infile outfile\n", argv[0]); return 1; } } void copy_file(FILE * infile, FILE * outfile) { int ch; int count = 0; while ((ch = fgetc(infile)) != EOF) { fputc(ch, outfile); count += 1; } fprintf(stderr, "%d characters copied\n", count); }