免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1941 | 回复: 1

[Linux] 用lseek+read函数读入文件不存在的位置,然后没有报错,程序并没有崩溃.为什么? [复制链接]

论坛徽章:
0
发表于 2013-07-24 18:31 |显示全部楼层
10可用积分
如下所示的程序/tmp/test1文件已经有内容了)

  1. #include <iostream>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. using namespace std;
  6. int main()
  7. {
  8.     int fd=open("/tmp/test1",O_RDONLY);
  9.     lseek(fd,2,SEEK_END);
  10.     cout << errno << endl;
  11.     char buf[4]={0};
  12.     int r=read(fd,buf,3);
  13.     cout << "r=" << r << ",errno=" << errno << "buf=" << buf << endl;
  14.     return 0;
  15. }
复制代码
程序用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 ...

论坛徽章:
17
处女座
日期:2013-08-27 09:59:352015亚冠之柏太阳神
日期:2015-07-30 10:16:402015亚冠之萨济拖拉机
日期:2015-07-29 18:58:182015年亚洲杯之巴勒斯坦
日期:2015-03-06 17:38:17摩羯座
日期:2014-12-11 21:31:34戌狗
日期:2014-07-20 20:57:32子鼠
日期:2014-05-15 16:25:21亥猪
日期:2014-02-11 17:32:05丑牛
日期:2014-01-20 15:45:51丑牛
日期:2013-10-22 11:12:56双子座
日期:2013-10-18 16:28:17白羊座
日期:2013-10-18 10:50:45
发表于 2013-07-24 18:31 |显示全部楼层
你应该看看文档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 the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP