首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

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

2012-08-25 
Linux环境,问一个关于fseek的问题代码如下:C/C++ code#includestdio.hint main(void){FILE *fpint i,j

Linux环境,问一个关于fseek的问题
代码如下:

C/C++ code
#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,谢谢!

[解决办法]
-1是不行的,因为已经超出了文件的左边界了,很明显是不合理的。

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

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

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

C/C++ code
   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 

热点排行