因爲C++也被標記了,我會用boost::filesystem
:
#include <boost/filesystem.hpp>
bool FileExist(const std::string& Name)
{
return boost::filesystem::exists(Name);
}
場景
顯然,提升使用stat
對POSIX和DWORD attr(::GetFileAttributesW(FileName));
在Windows(注背後:我這裏提取了代碼的相關部分,可能是我做錯了,但應該是這樣)。
基本上,除了返回值,boost會檢查errno值以檢查文件是否真的不存在,或者您的stat因爲其他原因失敗。
#ifdef BOOST_POSIX_API
struct stat path_stat;
if (::stat(p.c_str(), &path_stat)!= 0)
{
if (ec != 0) // always report errno, even though some
ec->assign(errno, system_category()); // errno values are not status_errors
if (not_found_error(errno))
{
return fs::file_status(fs::file_not_found, fs::no_perms);
}
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::status",
p, error_code(errno, system_category())));
return fs::file_status(fs::status_error);
}
#else
DWORD attr(::GetFileAttributesW(p.c_str()));
if (attr == 0xFFFFFFFF)
{
int errval(::GetLastError());
if (not_found_error(errval))
{
return fs::file_status(fs::file_not_found, fs::no_perms);
}
}
#endif
not_found_error
爲Windows和POSIX分別定義:
的Windows:
bool not_found_error(int errval)
{
return errval == ERROR_FILE_NOT_FOUND
|| errval == ERROR_PATH_NOT_FOUND
|| errval == ERROR_INVALID_NAME // "tools/jam/src/:sys:stat.h", "//foo"
|| errval == ERROR_INVALID_DRIVE // USB card reader with no card inserted
|| errval == ERROR_NOT_READY // CD/DVD drive with no disc inserted
|| errval == ERROR_INVALID_PARAMETER // ":sys:stat.h"
|| errval == ERROR_BAD_PATHNAME // "//nosuch" on Win64
|| errval == ERROR_BAD_NETPATH; // "//nosuch" on Win32
}
POSIX:
bool not_found_error(int errval)
{
return errno == ENOENT || errno == ENOTDIR;
}
這是檢查,如果它存在的目的,例如你打算打開文件,如果它存在,或打印錯誤消息,或其他? –
它應該很好。我會專門檢查Windows和POSIX,默認情況下是POSIX類似的東西。您應該也可以定義一個項目特定的操作系統,因爲這些名稱本身可能會隨系統而變化。 – Jiminion
@MatsPetersson:打印錯誤消息是其中一個用例。 –