我正在尝试使用read()在C程序中读取二进制数据,但EOF测试不起作用。相反,它一直运行,读取文件的最后一个比特。
#include <stdio.h>
#include <fcntl.h>
int main() {
// writing binary numbers to a file
int fd = open("afile", O_WRONLY | O_CREAT, 0644);
int i;
for (i = 0; i < 10; i++) {
write(fd, &i, sizeof(int));
}
close(fd);
//trying to read them until EOF
fd = open("afile", O_RDONLY, 0);
while (read(fd, &i, sizeof(int)) != EOF) {
printf("%d", i);
}
close(fd);
}
gcc -Wall
编译的习惯,注意警告(并修复它们!),在使用read
/write
时要包含<unistd.h>
。 - Paul R