在 Windows 与 Unix 平台上面得 C/C++ 之中,都标准提供了 access 函数得实现,只不过参数会有一些不同。
为了确保跨平台编译、兼容得通用、及一致性,所以人们需要显示定义:
#if defined(_WIN32)
#include <io.h>
#else
#include <unistd.h>
#endif
#ifndef R_OK
#define R_OK 4 /* Test for read permission. */
#endif
#ifndef W_OK
#define W_OK 2 /* Test for write permission. */
#endif
#ifndef X_OK
#define X_OK 1 /* Test for execute permission. */
#endif
#ifndef F_OK
#define F_OK 0 /* Test for existence. */
#endif
当我们期望通过 access 函数来判定文件是否存在时,可以实现以下得函数:
bool File::Exists(const char* path) noexcept {
if (NULL == path) {
return false;
}
return access(path, F_OK) == 0;
}
鉴于 Windows 与 Unix 平台上面,对于 access 函数参数得宏值定义不同,所以人们需要定义一个内部枚举。
en