#include <stdio.h>
void filecopy(FILE *infile, FILE *outfile);
int main(int argc, char *argv[]) { FILE *infile, *outfile; if (argc == 1) /* copy stdin to stdout */ filecopy(stdin, stdout); else { // argc > 1 if ((infile = fopen(*++argv, "r")) == NULL) { fprintf(stderr, "Can't open %s
", *argv); exit(1); } if (argc == 2) { filecopy(infile, stdout); fclose(infile); } else if (argc == 3) { if ((outfile = fopen(*++argv, "w")) == NULL) { fprintf(stderr, "Can't open %s
", *argv); exit(1); } filecopy(infile, outfile); fclose(infile); fclose(outfile); } else fprintf(stderr, "Extra CL args
", *argv); } }
void filecopy(FILE *infile, FILE *outfile) { int ch; while ((ch = fgetc(infile)) != EOF) fputc(ch, outfile); }
|
% cc -o copy copy.c
% copy Where are you? [Enter Ctrl-D]
Where are you?
% cat source.txt
Where are you?
% copy < source.txt
Where are you?
% copy < source.txt > dest.txt
% cat dest.txt
Where are you?
% copy source.txt
Where are you?
% rm dest.txt
% copy source.txt dest.txt
% cat dest.txt
Where are you?
% copy source.txt dest.txt xyz
Extra CL args
|