#include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <unistd.h>
6 #include <stdlib.h>
7 #include <string.h>
int main(){
9 int fd;
10 char *buf="pengyuandan snail\n";
11 fd=open("./file1",O_RDWR);
14 if(fd==-1){
15 printf("open file failed\n");
16 fd=open("./file1",O_RDWR|O_CREAT,0600);
17 if(fd>0){
18 printf("creat file success!\n");
19 }
20 }
21
22 printf("open success fd=%d\n",fd);
23 int n_write=write(fd,buf,strlen(buf));
24 if(n_write!=-1){
25 printf("write %d",n_write);
26 }
27 //读取之后再进行重新打开fd
28 close(fd);
29 fd=open("./file1",O_RDWR);
30
char*readbuf;
32 readbuf=(char*)malloc(sizeof(char)*n_write+1);
33
34 int n_read=read(fd,readbuf,n_write);
35 printf("read=%d,context:%s\n",n_read,readbuf);
36
37 close(fd);
return 0;
}
Linux文件读取操作 1 -重新打开 2-把光标移头再读
最新推荐文章于 2024-05-21 17:16:50 发布