免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4434 | 回复: 4
打印 上一主题 下一主题

lseek返回值问题 [复制链接]

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-01-22 14:31 |显示全部楼层 |倒序浏览
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
        int fd;
        char buf[20];
        int size;
        off_t location;
        char * filename = "tt.dat";

        if( (fd = open(filename,O_RDWR | O_CREAT | O_TRUNC)) == -1){
                perror("open");
                return 1;
        }

        size = write(fd,"Hello C Programming!\n",20);
        if(size <0){
                perror("write");
                return 1;
        }


        printf("%d bytes write to %s successfully!\n",size,filename);
        printf("the offset now is: %d\n",lseek(fd,0,SEEK_CUR));
        if( (location = lseek(fd,5,SEEK_SET) > -1)){
                printf("after lseeked %d .the offset now is: %d\n",location,lseek(fd,0,SEEK_CUR));
        }

        size = read(fd,buf,5);
        if(size <0){
                perror("read");
                return 1;
        }
        printf("%d bytes(\"%s\") read from  %s successfully!\n",size,buf,filename);
        printf("the offset now is: %d\n",lseek(fd,0,SEEK_CUR));
        return 0;
}

返回:
20 bytes write to tt.dat successfully!
the offset now is: 20
after lseeked 1 .the offset now is: 0
5 bytes(" C Pr") read from  tt.dat successfully!
the offset now is: 10

问:after lseeked 1 .the offset now is: 0为什么不是预期要得到的:after lseeked 5 .the offset now is: 5

[ 本帖最后由 FinalBSD 于 2008-1-22 14:52 编辑 ]

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
2 [报告]
发表于 2008-01-22 14:39 |显示全部楼层
原帖由 cugb_cat 于 2008-1-22 14:37 发表
因为你这句的括号括错地方了

if( (location = lseek(fd,5,SEEK_SET) > -1)){
                printf("after lseeked %d .the offset now is: %d\n",location,lseek(fd,0,SEEK_CUR));
        }

果然是,编译居然没错误。。谢谢啦!

[ 本帖最后由 FinalBSD 于 2008-1-22 14:40 编辑 ]

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
3 [报告]
发表于 2008-01-22 14:46 |显示全部楼层
有新问题啊:
GNU/Linux下得到预期的输出:
after lseeked 5 .the offset now is: 5
FreeBSD下得到
after lseeked 5 .the offset now is: 0

man 里面都说:Upon successful completion, lseek() returns the resulting offset location
     as measured in bytes from the beginning of the file.

纳闷呢

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
4 [报告]
发表于 2008-01-22 14:56 |显示全部楼层
原帖由 cugb_cat 于 2008-1-22 14:54 发表
这可能是不同编译器求值顺序不同的缘故?
你把lseek(SEEK_CUR)放到一个单独的语句中试试?

3和5行输出又是对的,诡异吧,不管它了,貌似这个问题很无聊,谢谢啦

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
5 [报告]
发表于 2008-01-22 14:59 |显示全部楼层
location2 = lseek(fd,0,SEEK_CUR);这样单独写之后还是不对
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP