1、文本复制 fgetc、fputc函数实现
#include <stdio.h> int main(void) { int ch; FILE *sfp; FILE *dfp; char sfilename[FILENAME_MAX]; char dfilename[FILENAME_MAX]; printf("source filename: "); scanf("%s", sfilename); printf("destination filename: "); scanf("%s", dfilename); if((sfp = fopen(sfilename, "r")) == NULL) printf("aSource file open failed. "); else { if((dfp = fopen(dfilename, "w")) == NULL) printf("aDestinatiom file open failed. "); else { while((ch = fgetc(sfp)) != EOF) fputc(ch, dfp); fclose(dfp); } fclose(sfp); } return 0; }
2、二进制复制、使用fread、fwrite函数实现
#include <stdio.h> int main(void) { int ch; FILE *sfp; FILE *dfp; char sfilename[FILENAME_MAX]; char dfilename[FILENAME_MAX]; printf("Source filename: "); scanf("%s", sfilename); printf("Destination filename: "); scanf("%s", dfilename); if((sfp = fopen(sfilename, "rb")) == NULL) printf("aSource file open failed. "); else { if((dfp = fopen(dfilename, "wb")) == NULL) printf("aDestination file open failed. "); else { int n; while(n = (fread(&ch, sizeof(int), 1, sfp)) > 0) fwrite(&ch, sizeof(int), 1, dfp); fclose(dfp); } fclose(sfp); } return 0; }