为什么调用 lseek 后读取的文件总是返回 0?

Win*_*ins 1 c linux ubuntu

我不明白为什么在 lseek 返回读取的 0 个字节后调用 read 。

//A function to find the next note for a given userID;
//returns -1 if at the end of file is reached;
//otherwise, it returns the length of the found note.
int find_user_note(int fd, int user_uid) {
    int note_uid = -1;
    unsigned char byte;
    int length;

    while(note_uid != user_uid) { // Loop until a note for user_uid is found.
        if(read(fd, &note_uid, 4) != 4) // Read the uid data.
            return -1; // If 4 bytes aren't read, return end of file code.
        if(read(fd, &byte, 1) != 1) // Read the newline separator.
            return -1;

        byte = length = 0;
        while(byte != '\n') { // Figure out how many bytes to the end of line.
            if(read(fd, &byte, 1) != 1) // Read a single byte.
                return -1; // If byte isn't read, return end of file code.

            //printf("%x ", byte);
            length++;
        }
    }
    long cur_position = lseek(fd, length * -1, SEEK_CUR ); // Rewind file reading by length bytes.

    printf("cur_position: %i\n", cur_position);

    // this is debug
    byte = 0;
    int num_byte = read(fd, &byte, 1);

    printf("[DEBUG] found a %d byte note for user id %d\n", length, note_uid);
    return length;
}
Run Code Online (Sandbox Code Playgroud)

当存在外部while循环时,变量长度值为34,上面的代码产生cur_position 5(所以lseek函数返回后肯定至少有34个字节),但是从函数read返回的变量num_byte总是返回0,即使有还有更多字节要读取。

有谁知道 num_byte 总是返回 0 的原因?如果这是我的代码中的错误,我没有看到它是什么。

仅供参考,上面的代码在以下机器上运行

$ uname -srvpio
Linux 3.2.0-24-generic #39-Ubuntu SMP Mon May 21 16:52:17 UTC 2012 x86_64 x86_64 GNU/Linux
Run Code Online (Sandbox Code Playgroud)

更新:

  • 我在这里上传完整的代码
  • 这是我尝试阅读的文件内容
$ sudo hexdump -C /var/notes
00000000  e8 03 00 00 0a 74 68 69  73 20 69 73 20 61 20 74  |.....this is a t|
00000010  65 73 74 20 6f 66 20 6d  75 6c 74 69 75 73 65 72  |est of multiuser|
00000020  20 6e 6f 74 65 73 0a                              | notes.|
00000027

$
Run Code Online (Sandbox Code Playgroud)

R..*_*R.. 6

如果length是小于off_t(例如,size_t在 32 位机器上)的无符号类型,那么length*-1将是一个巨大的值(大约 4GB 左右)。这可能是问题所在。将 的结果存储lseek到 a long(同样,如果它是 32 位)将应用实现定义的转换,可能是截断,这再次给您留下一个小值。

我看到你的机器是 64 位的,但也许你运行的是 32 位的用户空间?

无论如何,为什么不在下面运行您的程序 strace以查看它执行哪些系统调用?这几乎肯定会很快解决问题。