title: Unable to Re-Open Files In C, Linux
body: <p>So I'm doing some very basic work with opening and closing files in C.</p>
  
  <p>I noticed that when I run the following code, I get strange output:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;stdlib.h&gt;
  
  main()
  {
     // first get rid of existing input.txt, which is guaranteed to exist
     pid_t pid = fork();
  
     //child code
     if (pid == 0) {
         char* command[4] = {"rm", "-f", "input.txt", NULL};
         execvp(command[0], command);
     }
  
  
     // parent code
     else {
         int status;
         wait(&amp;status);
     }
  
     // initialize file descriptor
     int fd;
  
     // open input.txt with given flags
     int flags = O_RDWR | O_CREAT;
     fd = open("input.txt", flags);
  
     // debug
     fprintf(stderr,"The openval is %d\n", fd);
  
     // now close it
     int closeval = close(fd);
  
     // debug
     fprintf(stderr,"The closeval is %d\n", closeval);
  
     // try to re-open-it with different flags
     flags = O_RDONLY;
     fd = open("input.txt", flags);
  
     // debug
     fprintf(stderr,"The new openval is %d\n", fd);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>The openval is 3
  The closeval is 0
  The new openval is -1
  </code></pre>
  
  <p>The first and second lines of output make sense to me. My big question is, why can I not open the file a second time?</p>
  
  <p>I figured at first that it might be because I was requesting to open it the second time using the following flags:</p>
  
  <pre><code>flags = O_RDWR;
  </code></pre>
  
  <p>My thought was that requesting write permissions would somehow be messed up by the previous open (even though that shouldn't be the case because I closed it, right?). So i tried the version from above that only asks to read the file, and still no luck.</p>
  
  <p>Is opening, closing, and then re-opening files like that just not an option?</p>
  
  <p>Edit: Here is the errno testing code and output</p>
  
  <pre><code>if(fd == -1) {
         char* error = strerror(errno);
         fprintf(stderr,"%s\n",error);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Permission denied
  </code></pre>