加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:37:51 所属栏目:百科 来源:网络整理
导读:我试图用read()读取C程序中的二进制数据,但EOF测试不起作用.相反,它永远运行,永远读取文件的最后一位. #include stdio.h#include fcntl.hint main() { // writing binary numbers to a file int fd = open("afile",O_WRONLY | O_CREAT,0644); int i; for (i
我试图用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,sizeof(int)) != EOF) {
    printf("%d",i);
  }
  close(fd);
}

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读