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

问题描述 投票:0回答:2

函数

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



预先感谢

c++ c fopen
2个回答
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")
}

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)
}

0
投票

我也在看同样的情况。我希望在输出数据文件的第一个原始数据中有一个数据/列标题,即使正在附加数据。因此,仅当文件不存在时,我才会将第一行打印为列标题。我刚刚在读取选项(“r”)中打开文件,并检查它是否返回 NULL。如果为 NULL,我将继续打印列标题,并继续附加数据。这个方法有什么问题吗?

    fp = fopen(file,"r");
    if(!fp)
    {
            fp = fopen(file,"a");
            fprintf(fp,"#col-1\tcol-2\tcol-3\n");
    }
    else
    {
            fclose(fp);
            fp = fopen(file,"a");
    }
    fprintf(fp,"%d,%d,%d\n",val1,val2,val3);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.