- 论坛徽章:
- 0
|
10可用积分
如下所示的程序/tmp/test1文件已经有内容了)
- #include <iostream>
- #include <fcntl.h>
- #include <unistd.h>
- #include <errno.h>
- using namespace std;
- int main()
- {
- int fd=open("/tmp/test1",O_RDONLY);
- lseek(fd,2,SEEK_END);
- cout << errno << endl;
- char buf[4]={0};
- int r=read(fd,buf,3);
- cout << "r=" << r << ",errno=" << errno << "buf=" << buf << endl;
- return 0;
- }
复制代码 程序用GCC4.4编译运行看起来并没有问题,程序
# ./a.out
0
r=0,errno=0buf=
# echo $?
0
我的问题: 既然SEEK_END定位到了文件末尾,那么lseek(fd,2,SEEK_ENDD)实际就指向了一个并不存在文件偏移量。
为什么lseek和read都没有报错,errno也没有设定任何的值? 本来我的预期是,lseek或者read都要报错,要们崩溃退出啊。
求解释!
|
最佳答案
查看完整内容
你应该看看文档man lseek,说的很清楚:如果 offset 比文件的当前长度更大,下一个写操作就会把文件“撑大(extend)”。这就是所谓的在文件里创造“空洞(hole)”。没有被实际写入文件的所有字节由重复的 0 表示。The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subse- quent reads of ...
|