lseek函數(九)

lseek函數(九)

 

 

 

 代碼:

 1 /*  
 2     標準C庫的函數
 3     #include <stdio.h>
 4     int fseek(FILE *stream, long offset, int whence);
 5 
 6     Linux系統函數
 7     #include <sys/types.h>
 8     #include <unistd.h>
 9     off_t lseek(int fd, off_t offset, int whence);
10         參數:
11             - fd:文件描述符,通過open得到的,通過這個fd操作某個文件
12             - offset:偏移量
13             - whence:
14                 SEEK_SET
15                     設置文件指針的偏移量
16                 SEEK_CUR
17                     設置偏移量:當前位置 + 第二個參數offset的值
18                 SEEK_END
19                     設置偏移量:文件大小 + 第二個參數offset的值
20         返回值:返回文件指針的位置
21 
22 
23     作用:
24         1.移動文件指針到文件頭
25         lseek(fd, 0, SEEK_SET);
26 
27         2.獲取當前文件指針的位置
28         lseek(fd, 0, SEEK_CUR);
29 
30         3.獲取文件長度
31         lseek(fd, 0, SEEK_END);
32 
33         4.拓展文件的長度,當前文件10b, 110b, 增加了100個字節
34         lseek(fd, 100, SEEK_END)
35         注意:需要寫一次數據
36 
37 */
38 
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 #include <unistd.h>
43 #include <stdio.h>
44 
45 int main() {
46 
47     int fd = open("hello.txt", O_RDWR);
48 
49     if(fd == -1) {
50         perror("open");
51         return -1;
52     }
53 
54     // 擴展文件的長度
55     int ret = lseek(fd, 100, SEEK_END);
56     if(ret == -1) {
57         perror("lseek");
58         return -1;
59     }
60 
61     // 寫入一個空數據
62     write(fd, " ", 1);
63 
64     // 關閉文件
65     close(fd);
66 
67     return 0;
68 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章