lseek
lseek.c
1 #include <sys/types.h> 2 #include <sys/stat.h> 3 #include <fcntl.h> 4 #include <unistd.h> 5 #include <stdio.h> 6 #include <string.h> 7 #include <stdlib.h> 8 9 int main(void) 10 { 11 12 char buf1[100]; 13 char buf2[100]; 14 15 while(1){ 16 17 // 打开/创建 18 int fd = open("./1.text",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR); //这个参数很重要 19 if(fd<0){ 20 perror("open failed"); 21 exit(1); 22 } 23 24 // 写 25 bzero(buf1,100); 26 printf("write : "); 27 fgets(buf1,100,stdin); 28 if( write(fd,buf1,strlen(buf1))<0 ){ 29 perror("write failed"); 30 exit(1); 31 } 32 33 // 关一下,要不然无法读出数据 34 close(fd); 35 36 37 // 打开(读模式) 38 fd = open("./1.text",O_RDWR); 39 40 // 读 41 42 lseek(fd,1,SEEK_SET); //控制文件读写位置(头部正偏一个字节!) 重点!! 43 44 bzero(buf2,100); 45 if( read(fd,buf2,strlen(buf1))<0 ){ 46 perror("read failed"); 47 exit(1); 48 } 49 50 printf("read : %s ",buf2); 51 52 // 关闭 53 close(fd); 54 55 if(strncmp(buf2,"quit",4)==0) 56 break; 57 } 58 59 60 return 0 ; 61 }
测试:
success !