赋值必须用括号括起来,而不仅仅是函数调用:
while ((reader = read(fd, temp, BUFFER_SIZE)) >= BUFFER_SIZE) ...
但是请注意,读取的字节数不能大于请求的字节数,并且取决于reader 的类型和符号,比较将使用有符号或无符号算术,使-1 的返回值大于@ 987654324@。为避免这种情况,reader 必须定义为 ssize_t 或其他一些有符号类型。
更复杂的是,BUFFER_SIZE 可以定义为无符号数量,例如 #define BUFFER_SIZE 4096U 或 #define BUFFER_SIZE sizeof(temp),即使 reader 具有有符号类型,这也会强制执行无符号算术...
这是一种更安全的方法:
unsigned char temp[BUFFER_SIZE];
ssize_t nread;
while ((nread = read(fd, temp, sizeof temp)) > 0) {
// handle nread bytes...
}
if (nread < 0) {
// handle read error
} else {
// reached end of file successfully
}
上述循环不会处理可能导致read 返回-1 的信号。
你可以为此添加一个特殊的测试:
unsigned char temp[BUFFER_SIZE];
ssize_t nread;
for (;;) {
nread = read(fd, temp, sizeof temp);
if (nread < 0) {
if (errno == EINTR) {
// read attempt was interrupted by signal, restart
continue;
}
fprintf(stderr, "read error: %s\n", strerror(errno));
break;
}
if (nread == 0) {
// normal end of file
break;
}
// handle nread bytes...
}