一、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