Question of reading and writing files after Lseek using the O_append flag to open files

Source: Internet
Author: User

1FD = open ("./newfile", o_rdwr| O_creat| O_append, s_irusr|s_iwusr);2 if(FD <0 )3 {4Perror ("Open");5        return-1;6 }7pos = Lseek (FD,2, seek_cur);8 9printf"pos:%d\n", POS);TenWN = Write (FD,"-\n",2); One if(WN <0 ) A { -Perror ("Write");  - Close (FD); the        return-1; - } -  - Close (FD); + return 0;

The above is lseek after the write operation, the content of the NewFile is 26 letters, the result of execution is:

[Email protected]:~/test/apu$./A
Pos:2
[Email protected]:~/test/apu$ cat NewFile
Abcdefghijklmnopqrstuvwxyz
-
[Email protected]:~/test/apu$

and read the operation:

1FD = open ("./newfile", o_rdwr| O_creat| O_append, s_irusr|s_iwusr);2     if(FD <0 )3     {4Perror ("Open");5         return-1;6     }7pos = Lseek (FD,2, seek_cur);8 9RN = Read (FD, BUF,3);Ten     if(Rn <0 ) One     { APerror ("Read"); - Close (FD); -         return-1; the     } -printf"buf:%s\n", buf);

[Email protected]:~/test/apu$./A
Buf:cde

This time Lseek played a role, this is from the third chapter of Apue an exercise, carefully look at the definition of o_append know, man a bit

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).

In combination with other information, O_append only in the write when the atomic position to the end of the operation, the program is equivalent to the previous lseek is overwritten, so it does not work.

Question of reading and writing files after Lseek using the O_append flag to open files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.