日期:2014-05-16  浏览次数:20549 次

用lseek+read函数读入文件不存在的位置,然后没有报错,程序并没有崩溃.为什么?
如下所示的程序:(/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都要报错,要们崩溃退出啊。

求解释!

------解决方案--------------------
可以lseek,有一种技术,叫空洞文件。但是读不出来东西。
------解决方案--------------------
楼上正解。
这个和内存不一样,如果是内存溢出,有可能破坏内存中重要的数据,会造成系统崩溃。