如何使用 stat 检查文件是否存在
问题:
你想使用 sys/stat.h POSIX 头文件中的 stat() 检查具有给定名称的文件是否存在。
解决方案
使用此函数:
file_exists_stat.cpp
#include <sys/stat.h>
/**
* 检查文件是否存在
* @return 当且仅当文件存在时为 true,否则为 false
*/
bool fileExists(const char* file) {
struct stat buf;
return (stat(file, &buf) == 0);
}如果你想用 C++ std::string 作为文件名,你可以使用这个等效版本:
file_exists_stat_string.cpp
#include <sys/stat.h>
/**
* 检查文件是否存在
* @return 当且仅当文件存在时为 true,否则为 false
*/
bool fileExists(const std::string& file) {
struct stat buf;
return (stat(file.c_str(), &buf) == 0);
}注意这些函数不检查文件是否是普通文件。它们只检查具有给定名称的某物(普通文件、UNIX 域套接字、FIFO、设备文件等)是否存在
有关详细的 stat() 参考,请参见 Opengroup stat 页面
如果你不确定 stat() 是否存在于你的环境中,你可以使用此处描述的 std::ifstream 方法
Check out similar posts by category:
Allgemein
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow