linux头文件引用问题

读文件尾的两个字节, 代码如下:

 

#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    1


int 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.都不用段错误

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值