title: How to delete existing file by using open() function in C?
body: <p>I am currently using the following line to get a file descriptor:</p>
  
  <pre><code>int fd = open(file_name, O_RDWR | O_APPEND | O_CREAT);
  </code></pre>
  
  <p>but it fails (** fd = -1 with Error: permission denied**) when the file already exists. I am using the access() function to see if the file already exists:</p>
  
  <pre><code>if (access(file_name, F_OK) != -1)
  {
     printf("file %s already exists! \n", file_name);
     remove(file_name);  /* delete the existing file */
     fd = open(file_name, O_RDWR | O_APPEND | O_CREAT);
  }
  </code></pre>
  
  <p>Is there a better way to use the open() function to get a file descriptor for the following two scenarios:</p>
  
  <ol>
  <li>if the file does not exist, create it and return a file descriptor</li>
  <li>if the file <strong>exists</strong>, delete it and create a new file, then return a file descriptor.</li>
  </ol>