Versions Compared

Key

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

Opening a file that is already open has implementation-defined behavior according to The C Standard, Section subclause 7.21.3p8 3 paragraph 8 [ISO/IEC 9899:2011]:

Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined. Whether the same file can be simultaneously open multiple times is also implementation-defined.

...

Code Block
bgColor#ffcccc
langc
#include <stdio.h>
 
void do_stuff(void) {
  FILE *logfile = fopen("log", "a");
  if (logfile == NULL) {
    /* Handle error */
  }

  /* Write logs pertaining to do_stuff() */
  fprintf(logfile, "do_stuff\n");

  /* ... */
}

int main(void) {
  FILE *logfile = fopen("log", "a");
  if (logfile == NULL) {
    /* Handle error */
  }

  /* Write logs pertaining to main() */
  fprintf(logfile, "main\n");

  do_stuff();
 
  /* ... */fclose(logfile);
  return 0;
}

However, the file log is opened twice simultaneously. The result is implementation-defined and potentially dangerous.

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 
void do_stuff(FILE *logfile) {
  /* Write logs pertaining to do_stuff() */
  fprintf(logfile, "do_stuff\n");

  /* ... */
}

int main(void) {
  FILE *logfile = fopen("log", "a");
  if (logfile == NULL) {
    /* Handle error */
  }

  /* Write logs pertaining to main() */
  fprintf(logfile, "main\n");

  do_stuff(logfile);
 
  /* ... */fclose(logfile);
  return 0;
}

Implementation Details

...

 Bibliography

[ISO/IEC 9899:2011] Subclause  7.21.3, "Files"