#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef BUFSIZ
#undef BUFSIZ
#define BUFSIZ 4096
#endif
/*
且目标文件和源文件不能一样,否则会清空文件内容,
源文件必须存在,目标文件可存在也可不存在,如果存在,内容会被覆盖掉。
*/
int main(int argc,char **argv)
{
char buf[BUFSIZ]
int msglen
if(argc!=3||strcmp(argv[1],argv[2])==0)
/*argc:命令行模式下,输入的参数数目。
argv:第一个参数的首地址。*/
{
fprintf(stderr,"********************************\n\n")
fprintf(stderr,"Please usage:%s source_file destination_file\nAnd source_file is different from destination_file\n\n",argv[0])
fprintf(stderr,"********************************\n")
exit(0)
}
FILE *fp_src,*fp_des
if((fp_src=fopen(argv[1],"r"))==NULL)
/*为空,则打开失败*/
{
fprintf(stderr,"open %s failed!\n",argv[1])
exit(1)
}
if((fp_des=fopen(argv[2],"w"))==NULL)
/*为空,则打开或创建失败*/
{
fprintf(stderr,"open/create %s failed!\n",argv[2])
exit(2)
}
while(fgets(buf,BUFSIZ,fp_src)!=NULL)
/*从源文件读,读失败或到达文件尾部时,返回NULL*/
{
if(fputs(buf,fp_des)==EOF)
/*写入目标文件,写入失败时,返回EOF;若成功返回写入的字节数*/
{
fprintf(stderr,"copy %s to %s failed!\n",argv[1],argv[2])
exit(3)
}
}
printf("copy %s to %s successful!\n",argv[1],argv[2])
return 0
}
不应对非文本文件使用fgetc等易受干扰的函数,建议用fread,fwrite读写二进制文件#include "stdio.h"
/* 保护硬盘,绝对不要一个字节一个字节复制 */
#define SIZEOFBUFFER 256*1024L /* 缓冲区大小,默认为256KB */
long filesize(FILE *stream)
{
long curpos, length
curpos = ftell(stream)
fseek(stream, 0L, SEEK_END)
length = ftell(stream)
fseek(stream, curpos, SEEK_SET)
return length
}
int copyfile(const char* src,const char* dest)
{
FILE *fp1,*fp2
int fsize,factread
static unsigned char buffer[SIZEOFBUFFER]
fp1=fopen(src,"rb")
fp2=fopen(dest,"wb+")
if (!fp1 || !fp2) return 0
for (fsize=filesize(fp1)fsize>0fsize-=SIZEOFBUFFER)
{
factread=fread(buffer,1,SIZEOFBUFFER,fp1)
fwrite(buffer,factread,1,fp2)
}
fclose(fp1)
fclose(fp2)
return 1
}
int main()
{
copyfile("file1.txt","file2.txt")
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)