C/C++ Windows 与 Unix 平台上面使用 access 访问文件函数

在 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 函数参数得宏值定义不同,所以人们需要定义一个内部枚举。

        enum FileAccess {
            Read                                = 1,
            Write                               = 2,
            ReadWrite                           = 3,
        };

其后,在通过定义得内部枚举,根据行为得不同实现具体得事务。

        bool File::CanAccess(const char* path, FileAccess access_) noexcept {
#if defined(_WIN32)
            if (NULL == path) {
                return false;
            }

            int flags = 0;
            if ((access_ & FileAccess::ReadWrite) == FileAccess::ReadWrite) {
                flags |= R_OK | W_OK;
            }
            else {
                if (access_ & FileAccess::Read) {
                    flags |= R_OK;
                }
                if (access_ & FileAccess::Write) {
                    flags |= W_OK;
                }
            }
            return access(path, flags) == 0;
#else
            int flags = 0;
            if ((access_ & FileAccess::ReadWrite) == FileAccess::ReadWrite) {
                flags |= O_RDWR;
            }
            else {
                if (access_ & FileAccess::Read) {
                    flags |= O_RDONLY;
                }
                if (access_ & FileAccess::Write) {
                    flags |= O_WRONLY;
                }
            }

            int fd = open(path, flags);
            if (fd == -1) {
                return false;
            }
            else {
                close(fd);
                return true;
            }
#endif
        }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值