Quickest way to check whether or not file exists
This question already has an answer here:
On Windows, there is PathFileExists().
On a POSIX system, you have stat() or access().
That said, if you check for existence of the file because your code needs the file, this is the wrong approach -- file systems are out of your program's control, so this would be a race condition, the only correct way would be to properly handle errors when opening the file.
You are thinking about the problem the wrong way. You shouldn't ever "check whether a file already exists", because that has an inherent TOCTOU race — in between the time you check whether the file exists, and the time you act on that information, another process may come along and change whether the file exists, rendering the check invalid.
What you do instead depends on why you want to know. One very common case is that you only want to create the file if it doesn't already exist, in which case you use the lower-level open
function in O_EXCL
mode:
int fd = open("whatever", O_WRONLY|O_CREAT|O_EXCL, 0666);
if (fd == -1 && errno == EEXIST) {
/* the file already exists */
} else if (fd == -1) {
/* report that some other error happened */
} else {
FILE *fp = fdopen(fd, "w");
/* write data to fp here */
}
Another very common case is that you want to create the file if it doesn't exist, or append new data to the file if it does; this can be done with the "a"
mode to fopen
or O_APPEND
flag to open
.
上一篇: 如何将我的Perl脚本打包到没有Perl的机器上运行?
下一篇: 检查文件是否存在的最快方法