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

前端之家收集整理的这篇文章主要介绍了c – 如何使用read()读取数据直到文件结尾?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用read()读取C程序中的二进制数据,但EOF测试不起作用.相反,它永远运行,永远读取文件的最后一位.
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. int main() {
  4.  
  5. // writing binary numbers to a file
  6. int fd = open("afile",O_WRONLY | O_CREAT,0644);
  7. int i;
  8. for (i = 0; i < 10; i++) {
  9. write(fd,&i,sizeof(int));
  10. }
  11. close(fd);
  12.  
  13. //trying to read them until EOF
  14. fd = open("afile",O_RDONLY,0);
  15. while (read(fd,sizeof(int)) != EOF) {
  16. printf("%d",i);
  17. }
  18. close(fd);
  19. }

解决方法

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

猜你在找的C&C++相关文章