六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 92|回复: 0

linux头文件引用问题

[复制链接]

升级  38.67%

28

主题

28

主题

28

主题

秀才

Rank: 2

积分
108
 楼主| 发表于 2013-2-4 14:54:40 | 显示全部楼层 |阅读模式
读文件尾的两个字节, 代码如下:
 
#include <stdio.h>#include <errno.h>#include <sys/types.h>#include <sys/stat.h>#include <string.h>//#include <unistd.h>#include <fcntl.h>#define MSG_ERR printf#define S_OK        0#define S_FAILED    1int main(int argc, char *argv[]){    char *filename = "test.txt";    int ret;    int r = S_FAILED;    int fd = -1;    int size = 0;    struct stat statBuf;    do {        if(stat(filename, &statBuf) != 0) {            printf("STAT file error.(%s)\n", strerror(errno));            break;        }        printf("file: %s length = %d", filename, statBuf.st_size);        if((fd = open(filename, O_RDONLY)) == -1) {            MSG_ERR("cannot open file: %s\n", filename);            break;        }        else{            MSG_ERR("open file %s ok\n", filename);        }        ret = lseek(fd, -2, SEEK_END);        //ret = lseek(fd, statBuf.st_size - 2, SEEK_CUR);        if(ret == -1)        {            MSG_ERR("seek file '%s' error:%s\n", strerror(errno), filename);            break;        }        else{            MSG_ERR("seek ok, ret = %d\n", ret);        }        //read the last 2 bytes        ret = read(fd, &size, 2);        if(ret != 2)        {            MSG_ERR("read file '%s' error:%s\n", strerror(errno), filename);            MSG_ERR("ret=%d", ret);            break;        }        else{            MSG_ERR("read ok, size = %d\n", size);        }        r = S_OK;       // УÑéͨ¹ý    }while(0);    if(fd != -1){        close(fd);    }    return r;}  头文件string.h和unistd.h, 在RHEL5.4_x86_64上测试结果:
1.只使用string.h结果错误
2.只使用unistd.h正确
3.都用正确
4.都不用段错误
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表