Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The following noncompliant code example shows a case where a file is removed while it is still open.

Code Block
bgColor#FFcccc
langc
char *file_name;
FILE *file;

/* initialize file_name */

file = fopen(file_name, "w+");
if (file == NULL) {
  /* Handle error condition */
}

/* ... */

if (remove(file_name) != 0) {
  /* Handle error condition */
}

/* continue performing I/O operations on file */

fclose(file);

...

Wiki Markup
This compliant solution uses the POSIX {{unlink()}} function to remove the file. The {{unlink()}} function  is guaranteed  to unlink the file from the file system hierarchy but keep the file on disk until all open instances of the file are closed \[[Open Group 2004|AA. Bibliography#Open Group 04]\].

Code Block
bgColor#ccccff
langc
FILE *file;
char *file_name;

/* initialize file_name */

file = fopen(file_name, "w+");
if (file == NULL) {
  /* Handle error condition */
}

if (unlink(file_name) != 0) {
  /* Handle error condition */
}

/*... continue performing I/O operations on file ...*/

fclose(file);

...