C语言函数编写:文件复制

请帮忙用C语言编写一个函数~~~功能是“文件复制”~~~谢谢~~

C语言实现一个简单的文件复制功能,Linux环境下。
思路步骤:(下代码最重要的逻辑步骤清晰)
第一步:打开源文件(要复制的文件),打开文件的方式以读的方式就可以了。
Linux C打开文件的库函数有:int open(const char *pathname,int flags),int open(const char *pathname,mode_t mode),以及 FILE *fopen(const char *path,const char *mode),FILE *fdopen(int fd,const char *mode),这几个函数,具体的使用方法就查看manual就可以了。
第二步:创建目标文件,所用的函数也是上面那几个。
第三步:读取文件。库函数有:size_t read(int fd,void *buf,size_t count),
size_t fread(void *ptr,size_t size,size_t nmemb,FILE *stream)
第三步:写入目标文件。用的库函数:size_t write(int fd,void *buf,size_t count),
size_t fwrite(void *ptr,size_t size,size_t nmemb,FILE *stream)
第四步:关闭文件。库函数:int fclose(FILE *fp) ,int close(int fd)
思路步骤就是这样子的了。下面是具体的代码实现。

#include
#include
#include
#include
#include
#include

int main(int argc,char *argv[])
{
int fd_source_file,fd_copy_file;//用接受int open()函数返回的值
//FILE *fp_source_file,*fp_copy_file;//如果用FILE *fopen()函数的话
int size_read,size_write;

char buf[1024];
char copy_file_name[50];
//检查参数的输入
if(argc<3)
{
printf("usage: ./a.out source_file_path copy_file_path\n");
exit(1);
}

//复制目标文件名
strcpy(copy_file_name,argv[2]);

//打开源文件
if( (fd_source_file=open(argv[1],O_RDONLY,00744))<0 )
{
perror("open source file error");
exit(1);
}

//创建目标文件
if( (fd_copy_file=open(argv[1],O_CREAT|O_RDWR)) <0 )
{
perror("create copy file error");
exit(1);
}

do
{
//读取文件内容
if( (size_read=read(fd_source_file,buf,1024)) <0 )
{
perror("read source file error");
exit(1);
}

//写入目标文件
if( (size_write=write(fd_copy_file,buf,sieze_read))<0 )
{
perror("wrire file error");
exit(1);
}

}while(size_read==1024)

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2007-07-10
一楼明显没明白楼主意思,他是要fputc()和fgetc()这两个函数的内容,而不是要你调用这两个函数,得,楼主您啊,还是去找到stdio.h这个文件打开看吧,找这两个函数看看它们怎么实现的,自己依葫芦划瓢做一个。
第2个回答  2007-07-11
楼主,我可是熬夜做出来给你的,你要是不给我分,你真太没人性了.我已经调试通过,但是没有象 copy *.* 这样的通配符.(请不要抄袭我的回答!)
#include<stdio.h>

main(int count,char *string[])
{ FILE *openfile,*destination;

strcat(string[2],string[1]);

if(count!=3)
{ printf("对不起,您的参数错误!\n");
getch();
exit(0);
}
if((openfile=fopen(string[1],"rb"))==NULL)
{ printf("对不起,您的源文件无法打开,或者不存在!\n");
getch();
exit(0);
}

if((destination=fopen(string[2],"wb"))==NULL)
{ printf("对不起,您的磁盘是否已经满了,或者不可以写入!\n");
getch();
exit(0);
}

printf("正在复制中......\n");
while(!feof(openfile))
fputc(fgetc(openfile),destination);
fclose(openfile);
fclose(destination);
system("cls");

printf("您的文件已经复制完成了!\n");
getch();

}
第3个回答  2007-07-10
#include"stdio.h" /*把fp文件复制到fq中*/
main()
{
FILE *fp,*fq;
if((fp=fopen("a.txt","r")==NULL)
{printf("cannot be opened\n");
exit(0);
}
if((fq=fopen("b.txt","w")==NULL)
{
printf("cannot be opende\n");
exit(1);
}
fputc(fgetc(fp),fq);
}本回答被提问者采纳