这是使用访问功能的好习惯
which is a good practice to use access function
我有以下代码,我也想在带有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
。
相关文章:
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 使用完数据结构后清空数据结构是一个好习惯吗?
- 让二传手返回布尔值是好习惯吗?
- 在同一C 源文件中使用多个名称空间是一个好习惯吗?
- 是聪明的指针是RAII的好习惯
- 使用 move-constructor 时将 self 重置为 nullptr 是一个好习惯吗?
- 将指针施放为成员函数作为C函数的指针是一个好习惯吗?
- 重建operator()是重建的好习惯
- 这是使用访问功能的好习惯
- 在cccallfuncnd中,我们通过指针.通过当地范围的指针是一个好习惯
- 在C 中,这是用字符串文字初始化char数组的好习惯
- 使用工厂朋友类分配新类,好习惯
- C++使用"this"是一个好习惯吗?
- 在每个可能的地方使用指针是否是一种好习惯
- 在销毁 pthread 互斥锁之前锁定它是否是一种好习惯
- 总是用{}初始化对象是个好习惯吗
- 这是传递可选/NULL shared_ptr参数的好习惯吗?
- 在头文件中定义c++函数是个好习惯吗?
- 大量使用静态成员变量是一种好习惯吗?
- 重命名和重新包含 std::unique_ptr 是一种好习惯吗?