title: What is the correct way of changing mode of fopen after checking if file exists?
body: <p>In my programm, I want to check if a logfile already exists and then write some data into it. Therefore I first opened it with mode "a". If this returned NULL, I reopend it  with "w", wrote the header and opened it with "a" again to append the data. But after some time I always got "Too many open files" as error - so obviously opening the same file to the same pointer still opens a new handle (I wasn't aware of that). But now I'm not entirely sure how to write that part of the code - do I always have to fclose and then fopen again?</p>
  
  <pre><code>FILE *target;       
  target= fopen (ComplPath, "a");
  
  if (target == NULL) 
  {   
      //fclose(target); ?!?!
      target= fopen (ComplPath, "w");
      if (target != NULL) 
      {
          fprintf(target, "Header-Text \n");  
          fprintf(target, "Data" \n);
          fclose(target);
      }
      else  
      {
          printf("Error at writeToLog: %s\n", strerror(errno));
      }  
  }
  else    
  {
      fprintf(target, "data");
      fclose(target);
  }   
  </code></pre>
  
  <p>See after the first if: Do I have to close the file before reopening it with "w"? It seems quite inefficient to close and reopen a file all the time. Or is there in general some better way to do this task?</p>