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

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

本文关键字:文件 追加 模式 何仅当 存在      更新时间:2023-10-16

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



提前致谢

为了避免争用条件,应在一次系统调用中打开并检查是否存在。在 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)
}

首先检查文件是否已存在。执行此操作的简单代码可能是这样的:

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

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

并像这样使用它:

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