title: How to use read() to read data until the end of the file?
body: <p>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.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;fcntl.h&gt;
  int main() {
  
    // writing binary numbers to a file
    int fd = open("afile", O_WRONLY | O_CREAT, 0644);
    int i;
    for (i = 0; i &lt; 10; i++) {
      write(fd, &amp;i, sizeof(int));
    }
    close(fd);
  
    //trying to read them until EOF
    fd = open("afile", O_RDONLY, 0);
    while (read(fd, &amp;i, sizeof(int)) != EOF) {
      printf("%d", i);
    }
    close(fd);
  }
  </code></pre>