调用了open,read,write,stat函数。
效果类似 cp 1.txt 2.txt
将1.txt中的内容复制到2.txt中,如果该目录下无2.txt将自动创建。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <error.h>
#include <unistd.h>
/*
函数为复制文件1的内容到文件2中,如果目录中无文件2将自动创建并设置为用户最高权限。
*/
int copy_file(const char *pathname1,const char *pathname2)
{
int fd1 = open(pathname1,O_RDONLY);
if(fd1 == -1)
{
perror("源文件打开失败,原因是");
return -1;
}
else
{
printf("源文件打开成功\n");
}
//获取文件属性
struct stat sb;
int s = stat(pathname1,&sb);
if(-1 == s)
{
perror("源文件属性获取失败,原因是");
return -1;
}
printf("源文件有%ld个字节\n",sb.st_size);
int fd2 = open(pathname2, O_CREAT | O_RDWR | O_APPEND,S_IRWXU | O_TRUNC);
if(fd2 == -1)
{
perror("目标文件打开失败,原因是");
return -1;
}
else
{
printf("目标文件打开成功\n");
}
char buf[sb.st_size];
int r1 = read(fd1,buf,sb.st_size);
if(-1 == r1)
{
perror("源文件读取失败,原因是");
return -1;
}
else
{
buf[r1]='\0';
printf("成功读取到源文件 %d个字符,内容是%s\n",r1,buf);
}
lseek(fd2,0,SEEK_SET);
int w = write(fd2,buf,sb.st_size);
if(-1 == w)
{
perror("写入目标文件失败,原因是");
return -1;
}
else
{
printf("源文件复制到目标文件成功\n");
}
char auf[sb.st_size];
lseek(fd2,-sb.st_size,SEEK_CUR);
int r2 = read(fd2,auf,sb.st_size);
if(-1==r2)
{
perror("目标文件读取失败,原因是");
return -1;
}
else
{
auf[r2]='\0';
printf("成功读取到目标文件 %d个字符,内容是%s\n",r2,auf);
}
close(fd1);
close(fd2);
return 0;
}
int main()
{
copy_file("1.txt","2.txt");
return 0;
}