有關O_APPEND標志和lseek()的使用


編程之路剛剛開始,錯誤難免,希望大家能夠指出。

 

O_APPEND表示以每次寫操作都寫入文件的末尾。
lseek()可以調整文件讀寫位置。

 

<<Linux/UNIX系統編程手冊>>上有這樣一個問題:當在O_APPEND打開后,然后用 lseek移動文件開頭,然后再用write寫,這個時候,數據會顯示在文件中的哪個位置?為什么?

先上代碼:

 1 #include <unistd.h>
 2 #include <string.h>
 3 #include <fcntl.h>
 4 #include <stdio.h>
 5 
 6 int main(void)
 7 {
 8     int fd = open("test_open.txt",O_RDWR | O_APPEND);
 9     if(fd < 0)
10     {
11         perror("open");
12     }
13 
14     int pos = lseek(fd,0,SEEK_SET);
15     if(pos != 0)
16     {
17         printf("lseek error\n");
18         return -1;
19     }
20 
21     int size =write(fd,"world",strlen("world"));
22     if(size != 5)
23     {
24         printf("write error\n");
25     }
26 
27     close(fd);
28     return 0;
29 }

 

test_open.txt的內容隨意,編譯運行程序會發現數據顯示在了文件最后,這個原因在APUE的3.8章節提到了:
  對於普通文件,寫操作從文件的當前偏移量處開始。如果在打開該文件時,指定了O_APPEND選項,則在每次寫操作之前,將文件偏移量設置在文件的當前結尾處。在一次成功寫入之后,該文件偏移量增加實際寫的字節數。

  其實就是在說O_APPEND會將lseek()的作用抵消掉。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM