LINUX 读取文件并将文件内容复制到另一个文件上

x33g5p2x  于2021-11-18 转载在 Linux  
字(0.9k)|赞(0)|评价(0)|浏览(525)

2.在/home下使用open()函数打开一个名为“学号.txt”的文件,如果该文件不存在,则创建此文件,通过使用read函数和write函数把“姓名.txt”的内容复制到“学号.txt”文件中。

接上文的
LINUX读取写入文件并打印出来(实例用的.txt)

已经建好的.txt

写代码:

#include<sys/types.h>
#include<sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main()
{
 int fd=0;
 int fd1=0;
 char filename[20]="/home/chenhao.txt";
 char filename1[20]="/home/01.txt";
//data
char buf[50]={0};

 fd=open(filename,O_CREAT|O_RDWR);
 if(fd==-1)
{
printf("open error\n");
return -1;
}

write(fd,buf,sizeof(buf));

off_t f_size=0;
f_size=lseek(fd,0,SEEK_END);
lseek(fd,0,SEEK_SET);
while(lseek(fd,0,SEEK_CUR)!=f_size)
{
 read(fd,buf,sizeof(buf));
}
 printf("%s\n",buf);

fd1=open(filename1,O_CREAT|O_RDWR);
if(fd1==-1)
{
printf("open error\n");
return -1;
}
write(fd1,buf,sizeof(buf));

close(fd);
close(fd1);
return 0;
}

就是打开二个通道 fd
读取buf 缓冲区
然后写入新建的fd1

相关文章

微信公众号