c++cfopen

How to open a file with append mode only if it exist


The function fopen("file-name",a); will return a pointer to the end of the file. If the file exist it is opened, otherwise a new file is created.
Is it possible to use the append mode and open the file only if it already exist? (and return a NULL pointer otherwise).



Thanks in advance


Solution

  • To avoid race conditions, opening and checking for existence should be done in one system call. In POSIX this can be done with open as it will not create the file if the flag O_CREAT is not provided.

    int fd;
    FILE *fp = NULL;
    fd = open ("file-name", O_APPEND);
    if (fd >= 0) {
      /* successfully opened the file, now get a FILE datastructure */
      fp = fdopen (fd, "a")
    }
    

    open may fail for other reasons too. If you do not want to ignore all of them, you will have to check errno.

    int fd;
    FILE *fp = NULL;
    do {
      fd = open ("file-name", O_APPEND);
      /* retry if open was interrupted by a signal */
    } while (fd < 0 && errno == EINTR); 
    if (fd >= 0) {
      /* successfully opened the file, now get a FILE datastructure */
      fp = fdopen (fd, "a")
    } else if (errno != ENOENT) { /* ignore if the file does not exist */
      perror ("open file-name");  /* report any other error */
      exit (EXIT_FAILURE)
    }