fread(buf,size,nmemb,fp): 从fp中将nmemb个size字节的内容读入到buf缓冲区中。如果没遇到文件结尾,其返回值应等于nmemb,否则返回实际读取的大小。
fwrite(buf,size,nmemb,fp); 将buf缓冲区中读取的nmemb个size字节的内容写入fp中。返回成功写入的项目数,正常情况下应等于nmemb,若写入发生错误,其返回值小于nmemb.
自定义缓存大小:
1 void copyFile(char* src, char* dst) 2 { 3 enum{SIZE = 4096}; 4 FILE *in, *out; 5 char buf[SIZE]; 6 long inCount = 0; 7 if ((in = fopen(src, "rb")) == NULL) { 8 printf("fail to open source file %s\n", src); 9 exit(EXIT_FAILURE); 10 } 11 if ((out = fopen(dst, "wb")) == NULL) { 12 printf("fail to open destination file %s\n", dst); 13 exit(EXIT_FAILURE); 14 } 15 while ((inCount = fread(buf, sizeof(char), SIZE, in)) > 0) 16 { 17 fwrite(buf, sizeof(char), inCount, out); 18 } 19 fclose(in); 20 fclose(out); 21 }
完全缓存:
1 void copyFull(char* src, char* dst) 2 { 3 FILE *in, *out; 4 char *buf; 5 6 if ((in = fopen(src, "rb")) == NULL) { 7 printf("fail to open source file %s\n", src); 8 exit(EXIT_FAILURE); 9 } 10 if ((out = fopen(dst, "wb")) == NULL) { 11 printf("fail to open destination file %s\n", dst); 12 exit(EXIT_FAILURE); 13 } 14 fseek(in, 0, SEEK_END); 15 long size = ftell(in); 16 buf = (char*)malloc(size); 17 rewind(in); 18 long len = fread(buf, sizeof(char), size, in); 19 if (len == size) 20 printf("success load cache\n"); 21 long len2 = fwrite(buf, sizeof(char), len, out); 22 if (len2 == len) 23 printf("success copy file\n"); 24 delete buf; 25 fclose(in); 26 fclose(out); 27 }