如何仅当文件存在时才使用追加模式打开文件
How to open a file with append mode only if it exist
函数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");}
相关文章:
- 如何在特定位置追加 json 文件
- 文件追加的方式是,它在每次保存C++后结束行
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- 为什么将追加'.o'附加到头文件末尾是先决条件?
- C++ - 将文本追加到仅具有 NTFS"追加数据"权限的文件
- 分段 追加和读取二进制文件时出错
- 追加到文本文件在循环中无法正常工作
- std::ofstream 追加文件
- 如何在C++的追加模式下清除文件
- WriteFileGather - 将缓冲区追加到文件
- 在文本文件中覆盖和追加行(C++)
- 正在追加二进制文件
- 如何仅当文件存在时才使用追加模式打开文件
- minizip追加到文件
- 将文本文件的内容追加到C++中的另一个文件
- 在 C++ 中覆盖文件(不追加)
- fseek 在"a"(追加)模式下打开文件时不起作用
- 使用 cpp 在 opencv 中的 xml 文件中追加元素
- 以追加模式打开文件,但截断文件
- C++ 不追加到文本文件