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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3180126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:48:18  来源:igfitidea点击:

How to use read() to read data until the end of the file?

cunix

提问by sekmet64

I'm trying to read binary data in a C program with read() but EOF test doesn't work. Instead it keeps running forever reading the last bit of the file.

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

回答by Jerry Coffin

readreturns the number of characters it read. When it reaches the end of the file, it won't be able to read any more (at all) and it'll return 0, not EOF.

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

回答by u0b34a0f6ae

You must check for errors. On some (common) errors you want to call read again!

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

If read() returns -1 you have to check errnofor the error code. If errno equals either EAGAINor EINTR, you want to restart the read()call, without using its (incomplete) returned values. (On other errors, you maybe want to exit the program with the appropriate error message (from strerror))

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

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

示例:来自 git 源代码的名为 xread() 的包装器