title: write(): Bad file descriptor
body: <p>I'm trying to learn basic IO functions in POSIX, I wrote the following code, but it does not work and a "Bad file descriptor" error is returned when I try to execute the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #include &lt;sys/stat.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(void)
  {
  
      int nfd;
      ssize_t ret;
  
      mode_t mode = S_IRWXU | S_IRWXG;
  
      nfd = openat(AT_FDCWD, "idx.txt", O_APPEND | O_SYNC | O_CREAT, mode);
  
      if (-1 == nfd)
      {
          perror("openat()");
          exit(EXIT_FAILURE);
      }
  
      ret = write(nfd, "HELLO", 5);
  
      if (-1 == ret)
      {
          perror("write()");
          exit(EXIT_FAILURE);
      }
  
      close(nfd);
  
      return 0;
  }
  </code></pre>
  
  <p>I want to write to the file in O_APPEND mode. But:</p>
  
  <pre><code>$ touch idx.txt # it does not work even if the file does not exist already
  $ ./a.out
  write(): Bad file descriptor
  </code></pre>