方法一:
这里主要 用到的函数是 open,read,write
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
char buff[1024];
int len;
int main(int argc, char const *argv[])
{
char const *src_path = argv[1];
char const *des_path = argv[2];
int fd,fd2;
fd = open(src_path,O_RDWR|O_CREAT);
fd2 = open(des_path,O_RDWR|O_CREAT);
while(len = read(fd,buff,1024))
{
write(fd2,buff,len);
}
return 0;
}
其中open 函数:
第一个参数为要打开文件的路径,第二个参数是功能flag,O_RDWR表示以读写方式打开文件,O_CREAT表示如果文件不存在则创建
返回一个文件描述符,表示打开了的文件
其中 read 函数:
第一个参数是一个文件描述符,表示:从该文件描述符表示的文件读取数据
第二个参数是把从文件读到的信息放在一个缓冲数组中
第三个参数是读一次读多少字节
其中 write 函数:
第一个参数,是把数据写到哪里(写到哪个文件描述符中)
第二个参数:把缓冲数组中的数据写到文件描述符中
第三个参数:表示一次写多少字节
注意:最好像上面代码那样用一个while循环来读写数据,这样的话,read 中的第三个参数就不用设置成太大,因为他会把数据全读完才退出循环
第二种方法:
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
char buff[1024];
int len;
int main(int argc, char const *argv[])
{
FILE *in,*out;
char const * src_path = argv[1]; //要被拷贝的文件路径
char const * des_path = argv[2]; //拷贝的文件放在哪里(路径)
in = fopen(argv[1],"r+");
out = fopen(argv[2],"w+");
while(len = fread(buff,1,sizeof(buff),in))
{
fwrite(buff,1,len,out);
}
return 0;
}
第三种方法
/* 文件拷贝 */
void copy_file(char *file_src, char *file_dst)
{
if((NULL == file_src) || (NULL == file_dst) || (0 != (access(file_src, F_OK))))
{
return;
}
FILE *fp1 = NULL;
FILE *fp2 = NULL;
int ch = 0;
if((NULL == (fp1 = fopen(file_src, "r"))) || (NULL == (fp2 = fopen(file_dst, "w"))))
{
return 1;
}
while(EOF != (ch = getc(fp1)))
{
putc(ch, fp2);
}
fclose(fp1);
fclose(fp2);
}