Linux的append函数,Linux API -- open 设置操作属性O_APPEND时的那点小事

一、open

int open (const char * pathname , int flags, ..../* 只有当你要创建文件时,才需要填写这第3个参数,用来指定文件权限 */) ;

问题1、我们都知道,open 的flags参数 有个文件操作属性叫 : O_APPEND;

现在提出问题: 如果我指定了O_APPEND属性, 那么我第一次读文件读写位置时,读写位置的值是多少?

答:结果是0,即文件的读写位置是文件头;

原因是这样的,使用O_APPEND属性后,这个效果只有在你每一次使用write函数时,才会生效,即当你每次调用write时,OS就会把文件的读写位置设置成文件尾部;而你之前做的所有工作,包括你调用lseek函数来修改文件读写位置,到了你每一次调用write函数时,操作系统还是会把读写位置设置成文件尾部!即所有的写操作都只能在文件尾部进行!

测试代码:

int main()

{

int fd;

fd = open("new.txt",O_RDWR | O_APPEND);

off_t Position = lseek(fd,0,SEEK_CUR);

cout << "1st time check the Position is : " << Position << endl;

char buf = 'G';

if(write(fd,&buf,1) == -1)

{

cout << "write is wrong!" << endl;

}

Position = lseek(fd,0,SEEK_CUR);

cout << "2nd time check the position after 1 write " << Position<< endl;

Position = lseek(fd,0,SEEK_SET);

cout << "3rd time check the positon ,after invoke lseek to set the pos :" << Position << endl;

buf = 'P';

if(write(fd,&buf,1) == -1)

{

cout << "wrong" << endl;

}

Position = lseek(fd,0,SEEK_CUR);

cout << "4th time check the postion,after 2 write :" << Position << endl;

close(fd);

return 0;

}

结果:

chance@chance-ThinkPad-T400:/home/workspace$ ./a.out

1st time check the Position is : 0

2nd time check the position after 1 write 14

3rd time check the positon ,after invoke lseek to set the pos :0

4th time check the postion,after 2 write :15

the result is 3

查看文件内容:

Hello World!

GP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值