title: bad file descriptor fileno
body: <p>I am having trouble using fcntl() and fileno. I am having trouble implementing a lock mechanism. However when I try to close a file I get the following error  <strong><em>fcntl: Bad file descriptor</em></strong>. I am using fileno to get the file description and I am getting -1. </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;unistd.h&gt;
  
  //args ==path to the file
  int main(int argc, char *argv[])
  {
      struct flock lock = {F_WRLCK, SEEK_SET,   0,      0,     0 };
      int fd;
      FILE* fp;
  
      lock.l_pid = getpid();
  
      if (argc &gt; 1) 
          lock.l_type = F_RDLCK;
  
      printf("%s\n", argv[1]);
  
      fp = fopen(argv[1], "w");
  
      if(fp==NULL)
      {
          perror("fopen");
          exit(1);
      }
  
      fd=fileno(fp);
  
      getchar();
  
      if (fcntl(fd, F_SETLKW, &amp;lock) == -1) {
          perror("fcntl");
          exit(1);
      }
  
      lock.l_type = F_UNLCK; 
  
  
      if (fcntl(fd, F_SETLK, &amp;lock) == -1) {
          perror("fcntl");
          exit(1);
      }
  
      close(fd);
  
      return 0;
  }
  </code></pre>