仅当文件存在时如何以追加模式打开文件

TTK*_*TTK 0 c c++ fopen

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



提前致谢

Leo*_*ayr 5

为了避免竞争条件,打开和检查是否存在应该在一个系统调用中完成。在 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")
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)