这是使用访问功能的好习惯

which is a good practice to use access function

本文关键字:功能 好习惯 访问      更新时间:2023-10-16

我有以下代码,我也想在带有GCC 4.8的Linux上工作

这与VS 2013一起使用

if ( _access( trigger->c_str(), 0 ) != -1 ) 
{
   ...
}

我知道在Linux上我可以使用功能:从"unistd.h"访问

有没有办法避免出现类似以下内容(更优雅的解决方案)?

#ifdef __linux__ 
    #include <unistd.h>
#endif
#ifdef __linux__ 
     if ( access( trigger->c_str(), 0 ) != -1 ) 
     {
          ...
     }
#else
     if ( _access( trigger->c_str(), 0 ) != -1 )
     {
          ...
     }
#endif

一个没有重复,也不依赖于宏定义(除了用于平台检测的预定义定义)的解决方案,但比 ArchPhor 的解决方案具有更多的样板:

#ifdef _WIN32 
    inline int access(const char *pathname, int mode) {
        return _access(pathname, mode);
    }
#else
#include <unistd.h>
#endif

我更喜欢检测窗口,并使用 posix 作为回退,因为窗口往往比 Linux 更常见。

另一个干净的解决方案是定义_CRT_NONSTDC_NO_WARNINGS并在窗口中继续使用 POSIX 标准access,而不发出弃用警告。作为奖励,这也禁用了使用标准strcpy而不是strcpy_s和类似的警告。后者也是标准的(在 C11 中),但可选且几乎没有任何其他 C 库实现它们(而且,并非所有 msvc 中的_s系列函数都符合 C11)。

还有另一种方法,仅标头解决方案。

#ifdef __linux__ 
    #include <unistd.h>
#else
    #define access _access
#endif
if ( access( trigger->c_str(), 0 ) != -1 ) 
{
      ...
}

它将在 Linux 系统上包含正确的文件,并将access替换为其他系统上的_access