我不明白为什么在 lseek 之后调用 read 会返回 0 读取的字节数。
//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, ¬e_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;
}
当存在外部while循环时,可变长度值为34,并且上面的代码产生cur_position 5(因此lseek函数返回后肯定至少有34个字节),但是从函数读取返回的变量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
更新:
- 我在这里上传完整的代码
- 这是我尝试阅读的文件内容
$ 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 $