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