//x像文件中写入数据
#includ<stdio.h>
#include<string,h>
#cinldue<fcntl.h>
#include,unistd.h>
int main(void)[
//打开文件
int fd = open("./shared.txt",O_WRONLY|O_CREAT|O_TRUNC,0664;
if(fd==-1){
perror("open");
return -1;
}
//向文件中写入数据
char* buf = "hello word";
ssize_t size=write(fd,buf,strlen(buf));
if(size==-1){
perror("write");
return -1;
}
printf("实际写入%ld个字节数\n",size);
//关闭文件
close(fd);
return 0;
}
//读取文件
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
int main(void){
//打开文件
int fd= open("./shared.txt",O_RDONLY);
if(fd==-1){
perror("open");
return -1;
}
//读取文件
char buf[64];//用来存储读取到的数据
ssize_t size=read(fd,buf,sizeof(buf)-1);
if(size==-1){
perror("read");
return -1;
}
printf("实际读取到%ld个字节\n",size);
printf("%s\n",buf);
//关闭文件
close(fd);
return 0;
}
2.顺序读写与随机读写
//调整文件的读写文字hi
#include<stdio.h>
#include<string.h>
#include<unisted.h>
//打开文件
open("./lseeek.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd==-1){
perror("open");
return -1;
}
//像文件中写入数据 hello word
char* buf="hello word!";
if(write(fd,buf,strlen(buf))==-1){
perror("write");
return -1;
}
//修改文件读写位置
IF(lseek(fd,-6,SEEK_END)==-1){
perror("lseek");
return -1;
}
//再次向文件写入数据 Liunx!
buf="liunx!";
if(write(fd,buf,strlen(buf))==-1){
perror("write");
return -1;
}
//关闭文件
close(fd);
2.文件描述符的复制
//文件描述符的复制
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main(void){
//打开文件,得到文件描述符 oldfd
int oldfd = open("./dup.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(old==-1){
perror("open")
return -1;
}
//复制文件描述符
int newfd=dup(oldfd);
if(newfd==-1){
perror("dup");
return -1;
}
printf("newfd=%d\n",newfd)
//通过oldf向文件写入helloword;
char*buf="hello world";
if(write(oldfd,buf,strlen(buf))==-1){
perror("write");
return -1;
}
//通过newfold调整文件读写位置
if(lseek(newfd,-6,SEEK_END)==-1){
peror("lseeek");
return -1;
}
buf="linux";
//通过oldfd再次向文件写入数据
if(write(oldfd,buf,strlen(buf))==-1){
perror("write");
return -1;
}
//关闭文件
close(newfd);
close(oldfd);
return 0;
}