标准 IO fread 与 fwrite 的使用(可以实现二进制流的读写)
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
例子 : 读写文件(二进制操作)
#include <stdio.h> int main(int argc, const char *argv[]) { FILE *fp = NULL; fp = fopen(argv[1],"w"); if(fp == NULL) { perror("fail open :"); return -1; } int a[] = {1,2,3,4}; //二进制流 fwrite(a,sizeof(int),sizeof(a)/sizeof(int),fp);//写二进制流 fclose(fp); //写完,关闭,再以只读方式打开 fp = fopen(argv[1],"r"); //以只读方式打开 if(fp == NULL) { perror("fail open :"); return -1; } int b[10] = {0}; fread(b,sizeof(int),4,fp); int i=0; for(i=0;i<4;i++) { printf("%d ",b[i]); } fclose(fp); return 0; }
例子: 实现文件内容复制
#include <stdio.h> int main(int argc, const char *argv[]) { FILE *fp_w = NULL; FILE *fp_r = NULL; fp_r = fopen(argv[1],"r"); //读 if(fp_r==NULL) { perror("r fail :"); return -1; } fp_w = fopen(argv[2],"w");//写 if(fp_w==NULL) { perror("w fail :"); return -1; } char a[10] = {0}; while(1) { //fread返回值,成功返回读取的个数,失败,返回EOF(-1),读取0个已经读到文件结束了 if(fread(a,sizeof(char),sizeof(a)/sizeof(char),fp_r) ==0 ) { perror("fread fail : "); break; } fwrite(a,sizeof(char),sizeof(a)/sizeof(char),fp_w); //写数据到文件 } puts("cp done"); fclose(fp_w); //关闭文件 fclose(fp_r); return 0; }