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 ループが存在し、上記のコードが cur_position 5 を生成する場合、変数長の値は 34 です (したがって、lseek 関数が戻った後に少なくとも 34 バイトが確実に存在します)。まだ読み取るバイトがあります。
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 $