C/File/File Copy
Copy a file
<source lang="cpp">
- include <stdio.h>
- include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *from, *to; char ch;
if(argc!=3) { printf("Usage: copy <source> <destination>\n"); exit(1); } /* open source file */ if((from = fopen(argv[1], "rb"))==NULL) { printf("Cannot open source file.\n"); exit(1); } /* open destination file */ if((to = fopen(argv[2], "wb"))==NULL) { printf("Cannot open destination file.\n"); exit(1); } /* copy the file */ while(!feof(from)) { ch = fgetc(from); if(ferror(from)) { printf("Error reading source file.\n"); exit(1); } if(!feof(from)) fputc(ch, to); if(ferror(to)) { printf("Error writing destination file.\n"); exit(1); } } if(fclose(from)==EOF) { printf("Error closing source file.\n"); exit(1); } if(fclose(to)==EOF) { printf("Error closing destination file.\n"); exit(1); } return 0;
}
</source>
Copy a file in reverse order
<source lang="cpp">
- include <stdio.h>
- include <stdlib.h>
int main(int argc, char *argv[]) {
long loc; FILE *in, *out; char ch;
if(argc != 3) { printf("Usage: revcopy <source> <destination>.\n"); exit(1); } if((in = fopen(argv[1], "rb")) == NULL) { printf("Cannot open input file.\n"); exit(1); } if((out = fopen(argv[2], "wb"))==NULL) { printf("Cannot open output file.\n"); exit(1); } /* find end of source file */ fseek(in, 0L, SEEK_END); loc = ftell(in); /* copy file in reverse order */ loc = loc-1; /* back up past end-of-file mark */ while(loc >= 0L) { fseek(in, loc, SEEK_SET); ch = fgetc(in); fputc(ch, out); loc--; } fclose(in); fclose(out); return 0;
}
</source>
Copy one file to another
<source lang="cpp">
- include <stdio.h>
- include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *in, *out; char ch; if(argc!=3) { printf("You forgot to enter a filename.\n"); exit(1); } if((in=fopen(argv[1], "rb")) == NULL) { printf("Cannot open input file.\n"); exit(1); } if((out=fopen(argv[2], "wb")) == NULL) { printf("Cannot open output file.\n"); exit(1); } while(!feof(in)) { ch = getc(in); if(ferror(in)) { printf("Read Error"); clearerr(in); break; } else { if(!feof(in)) putc(ch, out); if(ferror(out)) { printf("Write Error"); clearerr(out); break; } } } fclose(in); fclose(out); return 0;
}
</source>