//linux学习路上的初学者
//使用前你需要先创建好两个文件 1.txt 2.txt 并在1.txt里面写好内容。

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fctl.h>
//----头文件
#define BUF_SIZE 100

int main()
{
int fd=open(“1.txt”,O_RDONLY,0666);
//只读的方式打开一个文件,后面的0666为权限,可以不写
if(fd==-1)
{
printf(“open read file error\r\n”);
return -1;
}
printf(“open read file ok\r\n”);
//判断文件是否被打开 这里代码写的很清楚
int fd1=open(“2.txt,O_WRONLY,0666”);
//解释同上
if(fd1=-1)
{
printf(“open write file error\r\n”);
return -1;
}
printf(“open read file OK\r\n”);
//判断文件是否被成功读取

char buf[BUF_SIZE]={0};
int ret=read(fd,buf,BUF_SIZE);//ret 接收fd(1.txt)读取到的内容
if(ret==-1)
{
printf(“read fd error\r\n”);
return -1;
}
while(ret)//等到读取至末尾循环就结束
{
write(fd1,buf,ret);//将读到的内容写到fd1(2.txt)里面
ret=read(fd,buf,ret);//继续读
}
close(fd);
close(fd1);//最后关闭两个文件
return 0;
}

Logo

更多推荐