如何仅在文件存在时使用追加模式打开文件

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

函数fopen("file-name",a);将return指向文件末尾的指针。如果文件存在,则打开它,否则创建一个新文件。
是否可以使用附加模式并仅在文件已存在时才打开文件? (并且 return 否则为 NULL 指针)。



提前致谢

首先检查文件是否已经存在。一个简单的代码可能是这样的:

int exists(const char *fname)
{
    FILE *file;
    if ((file = fopen(fname, "r")))
    {
        fclose(file);
        return 1;
    }
    return 0;
}

如果文件不存在,它将return 0...

并像这样使用它:

if(exists("somefile")){file=fopen("somefile","a");}

为避免竞争条件,打开和检查是否存在应在一个系统调用中完成。在 POSIX 中,这可以通过 open 完成,因为如果未提供标志 O_CREAT,它将不会创建文件。

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 也可能由于其他原因而失败。如果您不想忽略所有这些,则必须检查 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)
}