首页 > 其他分享 >lseek的使用问题

lseek的使用问题

时间:2022-08-25 19:34:55浏览次数:47  
标签:lseek int 问题 fd2 fd 使用 include buf

当使用追加标识符打开一个文件以便读写时:

1.能否使用lseek在任意位置开始读

2.能否使用lseek更新文件中任一部分的数据

 1 #include<stdio.h>
 2 #include<unistd.h>
 3 #include<stdlib.h>
 4 #include<string.h> 
 5 #include<fcntl.h>
 6 
 7 int main()
 8 {
 9   char buf_1[80];
10 //在当前目录下创建a.txt文件并写入“123456”
11   int fd = open("./a.txt",O_RDWR|O_CREAT|O_APPEND,0766);
12   write(fd,"123456",strlen("123456"));
13   lseek(fd,3,SEEK_SET);//从起始偏移3字符
14   read(fd,buf_1,sizeof(buf_1));
15   close(fd);
16 
17   char buf_2[80];
18   char str[40]="abcde";
19   int fd2 = open("./a.txt",O_RDWR|O_APPEND);
20   lseek(fd2,3,SEEK_SET);
21   write(fd2,"str,strlen(str));//尝试从4位置开始写入
22 
23   lseek(fd2,0,SEEK_SET); //write后会将指针置尾,重新将其置0
24   read(fd2,buf_2,sizeof(buf_2));
25   printf("read buf_2 ---->%s\n",buf_2);
26   close(fd2);
27 
28    return 0 ;
29 
30 }    

输出结果

由此可见 使用O_APPEND时可在任意位置读,但是所写都会追加到末尾。

 

标签:lseek,int,问题,fd2,fd,使用,include,buf
From: https://www.cnblogs.com/jie-xi/p/16625471.html

相关文章