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

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

问题描述

我想在C程序的读读取二进制数据(),但EOF测试不起作用。相反,它保持运行永远读取文件的最后一位。

 的#include<&stdio.h中GT;
#包括LT&;&fcntl.h GT;
诠释主(){  //写入二进制数到文件
  INT FD =打开(å文件,O_WRONLY | O_CREAT,0644);
  INT I;
  对于(I = 0; I&小于10;我++){
    写(FD,和放大器;我的sizeof(INT));
  }
  关闭(FD);  //想读他们,直到EOF
  FD =打开(å文件,O_RDONLY,0);
  而(读(FD,和放大器;!我的sizeof(int)的)= EOF){
    的printf(%D,我);
  }
  关闭(FD);
}


解决方案

返回读取的字符数。当它到达该文件的结束时,它将无法读取任何更多(在所有),它会返回0,不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 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.

这篇关于如何使用读(),直到该文件的结束读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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