如何使用read()读取数据直到文件结束?

时间:2010-07-05 14:08:36

标签: c unix

我正在尝试使用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);
}

3 个答案:

答案 0 :(得分:20)

read返回它读取的字符数。当它到达文件末尾时,它将无法再读取(根本不会),它将返回0,而不是EOF。

答案 1 :(得分:3)

您必须检查错误。在某些(常见)错误上,您想再次调用read!

如果read()返回-1,则必须检查errno是否有错误代码。如果errno等于EAGAINEINTR,则需要重新启动read()调用,而不使用其(不完整的)返回值。 (关于其他错误,您可能希望使用相应的错误消息(来自strerror)退出程序)

示例:a wrapper called xread() from git's source code

答案 2 :(得分:0)

POSIX rasys返回== 0表示文件结尾

http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html

  

如果没有进程打开管道进行写入,read()将返回0以指示文件结束。

这确认了Jerry's answer

EOF由某些ANSI函数返回,例如man getc说:

  

fgetc(),getc()和getchar()将读取的字符作为无符号字符串转换为文件末尾或错误的int或EOF。

     

ungetc()在成功时返回c,或在出错时返回EOF。

因此,在这种情况下,您仍然无法使用它来区分错误和文件结尾,因此需要feof

另请参阅:How to use EOF to run through a text file in C?

相关问题