如何使用 read() 读取数据直到文件结束? [英] How to use read() to read data until the end of the file?

查看:56
本文介绍了如何使用 read() 读取数据直到文件结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 read() 读取 C 程序中的二进制数据,但 EOF 测试不起作用.相反,它会一直运行读取文件的最后一位.

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.

#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);
}

推荐答案

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

read returns 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() 读取数据直到文件结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆