#include
#include
#include
#ifdef BUFSIZ
#undef BUFSIZ
#define BUFSIZ 4096
#endif
/*
使用格式:mcpy 源文件 目标文件
且目标文件和源文件不能一样,否则会清空文件内容,
源文件必须存在,目标文件可存在也可不存在,如果存在,内容会被覆盖掉。
*/
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;
}
方法1
#include
#include
void main()
{
char filename[100],filename1[50],filename2[50];
printf("请输入要读的文件名:");
scanf("%s",filename1);
printf("请输入要写的文件名:");
scanf("%s",filename2);
sprintf(filename,"copy %s %s /y>nul",filename1,filename2);
system(filename);
}
方法2
#include
void main()
{
FILE *source,*object;
size_t readlen;
char filename1[50],filename2[50];
char diskbuffer[8192];
printf("请输入要读的文件名:");
scanf("%s",filename1);
printf("请输入要写的文件名:");
scanf("%s",filename2);
source=fopen(filename1,"rb");
if (source==NULL)
{
fclose(source);
return;
}
object=fopen(filename2,"wb");
do
{
readlen=fread(diskbuffer,1,8192,source);
fwrite(diskbuffer,1,readlen,object);
}while(!feof(source));
fclose(object);
fclose(source);
}
打开两个文件,从一个文件读数据,写入到另一个文件,例如: //------{ FILE *fp1,fp2; char c; fp1=fopen("dat.txt","r"); /*打开
//程序完成的操作:将D盘下 1.txt 文件中内容拷贝至 2.txt 文件中
#include
#include
void FileCopy(FILE *,FILE *);//拷贝子程序申明
void main(void)
{
FILE *fpin, *fpout;
if((fpin = fopen("D:\1.txt","rb")) == NULL)
{
printf("1 can't open file! /n");//文件打开失败打印输出
return;
}
if((fpout = fopen("D:\2.txt","wb")) == NULL)
{
printf("2 can't open file! /n");
return;
}
FileCopy(fpin,fpout);
fclose(fpin);
fclose(fpout);
fpin = NULL;
fpout = NULL;
printf("~~~~~~~~~~~~~~~~~~");
return;
}
void FileCopy(FILE *fpin, FILE *fpout)
{
char ch;
ch = getc(fpin);
while(!feof(fpin))
{
putc(ch,fpout);
ch = getc(fpin);
}
}
求加分 哈哈
#include
int main()
{
FILE *fp1,*fp2;
char buf[1024];
fp1=fopen("C:/1.dat","rb");
fp2=fopen("C:/2.dat","wb");
fread(buf,1024,1,fp1);
while(!feof(fp1))
{
fwrite(buf,1024,1,fp2);
fread(buf,1024,1,fp1);
}
fclose(fp1);
fclose(fp2);
}