Wednesday, September 27, 2006

O_APPEND/lseek/pwrite

在读Marc Rochkind的Advanced Unix Programming(AUP),2.14节在描述pwrite和O_APPEND的时候,觉得简单了一点:
如果以O_APPEND打开文件,pwrite的行为和write完全一致,offset参数完全被忽略
但是,文件描述符指向的文件描述中的实际偏移呢?由于参数offset和实际偏移都用了英文offset表述,我产生了混淆,写了个程序e,测试了一下:
#include < unistd.h >
#include < sys/types.h >
#include < fcntl.h >
#include < errno.h >
#include < sys/stat.h >
#include < stdlib.h >

int main(int argc,char* argv[])
{
int fd;
off_t where;
ssize_t size;
if ((fd=open("tt",O_WRONLY|O_APPEND))==-1){
perror("open failed!");
exit(-1);
}
if ((where=lseek(fd,0,SEEK_CUR))==-1){
perror("lseek failed!");
exit(-1);
}
printf("current pos is %ld\n",where);
if ((size=pwrite(fd,"0123456789",10,0))==-1){
perror("write failed!");
exit(-1);
}
if ((where=lseek(fd,0,SEEK_CUR))==-1){
perror("lseek failed!");
exit(-1);
}
printf("current pos is %ld\n",where);
exit(0);
}
设tt是个含0123456789\n的字符文件,在linux和aix环境中其结果如下
#cat tt
0123456789
#./e
current pos is 0
current pos is 0
#cat tt
0123456789
0123456789#
据此得出的结论:
1、即使以O_APPEND方式打开文件,文件描述符指向的当前偏移位置仍为0,只是write在操作这种文件时隐含调用了lseek将文件偏移位置移至文件尾部
2、pwrite在操作以O_APPEND方式打开的文件时,与write一样,从尾部开始写,同时,pwrite的offset参数不起任何作用,且文件描述符指向的当前偏移位置也不受任何影响
如果将
if ((size=pwrite(fd,"0123456789",10,0))==-1){
改成
if ((size=write(fd,"0123456789",10))==-1){
起结果为
#cat tt
0123456789
#./e
current pos is 0
current pos is 21
#cat tt
0123456789
0123456789#
印证了结论1

0 comments: