標籤:
1 fd = open("./newfile", O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR); 2 if ( fd < 0 ) 3 { 4 perror("open"); 5 return -1; 6 } 7 pos = lseek(fd, 2, SEEK_CUR); 8 9 printf("pos:%d\n",pos);10 wn = write(fd, "-\n", 2);11 if ( wn < 0 )12 {13 perror("write"); 14 close(fd);15 return -1;16 }17 18 close(fd);19 return 0;
以上是lseek後的寫操作,newfile內容是26個字母,執行得到的結果是:
[email protected]:~/test/apu$ ./a
pos:2
[email protected]:~/test/apu$ cat newfile
abcdefghijklmnopqrstuvwxyz
-
[email protected]:~/test/apu$
而進行讀操作:
1 fd = open("./newfile", O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR); 2 if ( fd < 0 ) 3 { 4 perror("open"); 5 return -1; 6 } 7 pos = lseek(fd, 2, SEEK_CUR); 8 9 rn = read(fd, buf, 3);10 if ( rn < 0 )11 {12 perror("read");13 close(fd);14 return -1;15 }16 printf("buf:%s\n",buf);
[email protected]:~/test/apu$ ./a
buf:cde
這次lseek起到了作用,這是來自APUE第三章一個練習題,仔細看看O_APPEND的定義就知道了,man 一下
O_APPEND
The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2).
結合一下其他資料,O_APPEND只是在write時原子性的把操作位置定位到末尾,程式中相當於前面那個lseek被覆蓋了,所以不起作用。
使用O_APPEND標誌開啟檔案對檔案進行lseek後進行讀寫的問題