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

cri*_*ian 4 c++ gcc visual-studio

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

这与VS 2013一起使用

if ( _access( trigger->c_str(), 0 ) != -1 ) 
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

我知道在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
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 6

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

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

我更喜欢检测窗口,并使用posix作为后退,因为windows往往比linux更常见.

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