1. fread/fwrite实现复制功能
#include <stdio.h> #include <stdlib.h> #define BUFFSIZE 4096 //执行: ./a.out file1 file2 //功能: 将file1的内容读取出来,写入file2,即复制 int main(int argc,char *argv[]) { char buffer[BUFFSIZE]; FILE *pRead,*pWrite; //读文件指针 写文件指针 int n; //检测是否输入file1和file2 if(argc!=3) { printf("main option error!\n"); return -1; } pRead = fopen(argv[1],"r"); //只读 文件必须已存在 if(!pRead) { printf("fopen argv[1] error!\n"); return -1; } pWrite = fopen(argv[2],"w"); //只写 若文件不存在,则创建 if(!pWrite) { printf("fopen argv[2] error!\n"); return -1; } //从pRead指向文件读取字符入buffer while( (n= fread(buffer,sizeof(char),sizeof(buffer),pRead))>0 ) { //检测从buffer写入pWrite指向文件的字符数,是不是等于读取字符数 if( fwrite(buffer,sizeof(char),n,pWrite)!=n ) { printf("fwrite error!\n"); return -1; } } if(n<0) //fread返回值<0,说明fread读取失败 { printf("fread error!\n"); return -1; } //复制结束后,要关闭文件 fclose(pRead); fclose(pWrite); return 0; }
时间: 2024-10-30 09:47:42