使用O_APPEND標誌開啟檔案對檔案進行lseek後進行讀寫的問題

來源:互聯網
上載者:User

標籤:

 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後進行讀寫的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.