c语言编写程序,完成把一个文件的内容复制到另一个文件中去。源文件的名字从键盘输入,目的文件的名字也

c语言编写程序,完成把一个文件的内容复制到另一个文件中去。源文件的名字从键盘输入,目的文件的名字也是从键盘输入。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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个回答  2016-04-19
#include <stdio.h>

int Copy_File(char* in_path,char* out_path)
{
FILE* in=NULL;
FILE* out=NULL;

if((in=fopen(in_path,"rb"))==NULL)
{
printf("无法打开源文件!\n");
return(1);
}

if((out=fopen(out_path,"wb+"))==NULL)
{
printf("无法创建目标文件!\n");
fclose(in);
return(1);
}

char data;

while(!feof(in))
{
if(1==fread(&data,sizeof(char),1,in))
fwrite(&data,sizeof(char),1,out);
}

fclose(in);
fclose(out);

return(0);
}

int main()
{
char in_path[256];
char out_path[256];

printf("请输入源文件的路径: ");
scanf("%s",in_path);

printf("请输入目的文件的路径: ");
scanf("%s",out_path);

if(Copy_File(in_path,out_path))
{
printf("拷贝失败!");
}else
printf("拷贝成功!");

return(0);
}本回答被提问者和网友采纳
相似回答