日期:2014-05-16  浏览次数:20732 次

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;       // D£?éí¨1y
    }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.都不用段错误

?