Linux环境,问一个关于fseek的问题

tongleicsd 2012-07-29 04:12:40
代码如下:

#include<stdio.h>

int main(void)
{
FILE *fp;
int i,j;
fp = fopen("tt","w");
for(i=0; i<10; i++)
{
j = fseek(fp,1L,SEEK_CUR);
printf("%d\n",j);
}
return 0;
}


结果:打印出10个0;
当我把j = fseek(fp,-1L,SEEK_CUR);就打出10个-1;

创建的是空文件,0字节,fseek遇到文件结尾不是应该返回-1吗?
求高手解答,或者详细解答fseek,谢谢!
...全文
86 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2012-07-29
  • 打赏
  • 举报
回复
打印-1你可以看一下errno是否为:

EINVAL The whence argument is not a proper value, or the resulting file offset would be negative for a regular file, block special file, or directory.
qq120848369 2012-07-29
  • 打赏
  • 举报
回复
-1是不行的,因为已经超出了文件的左边界了,很明显是不合理的。

1是可以的,fseek先清空自己的buffer(包括fflush刷out buffer),然后调lseek进行偏移。

然后lseek是允许超出文件右边界的,也就是可以超出文件末尾到文件外部,常用lseek+write扩充文件尺寸技巧。

至于为什么是0,这里解释清楚:

   The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent
reads of data in the gap shall return bytes with the value 0 until data is actually
written into the gap.

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧