C语言中access/_access函数的用法

本篇内容介绍了“C语言中access/_access函数的用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

我们提供的服务有:成都做网站、成都网站制作、微信公众号开发、网站优化、网站认证、天镇ssl等。为千余家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的天镇网站制作公司

在Linux下,access函数的声明在文件中,声明如下:

int access(const char *pathname, int mode);

access函数用来判断指定的文件或目录是否存在(F_OK),已存在的文件或目录是否有可读(R_OK)、可写(W_OK)、可执行(X_OK)权限。F_OK、R_OK、W_OK、X_OK这四种方式通过access函数中的第二个参数mode指定。如果指定的方式有效,则此函数返回0,否则返回-1。

在Windows下没有access函数,但在文件中有_access函数,声明如下:

int _access(const char* _Filename, int _AccessMode);

windows下的函数_access与linux下的access函数功能类似,用来判断指定的文件或目录是否仅存在(00),已存在的文件或目录是否有仅读(04)、仅写(02)、既可读又可写(06)权限。这四种方式通过_access函数中的第二个参数mode指定,如果mode传入的值不是0或2或4或6,调用此函数则会crash。如果指定的方式有效,则此函数返回0,否则返回-1。

以下是测试代码(access.cpp):

#include "access.hpp"#include #include #include #ifdef _MSC_VER#include #else#include #endifnamespace access_ {int test_access_1(){#ifdef _MSC_VER const std::string path{ "E:/GitCode/Messy_Test/" }; const std::vector names {"testdata", ".gitignore", "src", "invalid"}; for (auto& name : names) { const std::string tmp = path + name; fprintf(stdout, "file or directory name: \"%s\": ", name.c_str()); if (_access(tmp.c_str(), 0) == 0) fprintf(stdout, "exist, "); else fprintf(stdout, "not exist, ");  if (_access(tmp.c_str(), 4) == 0) fprintf(stdout, "only has read premission, "); else fprintf(stdout, "does not have read premission, "); if (_access(tmp.c_str(), 2) == 0) fprintf(stdout, "only has write premission, "); else fprintf(stdout, "does not have write premission, "); if (_access(tmp.c_str(), 6) == 0) fprintf(stdout, "has both read and write premission\n"); else fprintf(stdout, "has neither read nor write premission\n"); }#else const std::vector names {"testdata", "CMakeLists.txt", "build.sh", "invalid"}; for (auto name : names) { fprintf(stdout, "file or directory name: \"%s\": ", name); if (access(name, F_OK) == 0) fprintf(stdout, "exist, "); else fprintf(stdout, "not exist, ", name);  if (access(name, R_OK) == 0) fprintf(stdout, "has read premission, "); else fprintf(stdout, "does not have read premission, "); if (access(name, W_OK) == 0) fprintf(stdout, "has write premission, "); else fprintf(stdout, "does not have write premission, "); if (access(name, X_OK) == 0) fprintf(stdout, "has execute premission\n"); else fprintf(stdout, "does not have execute premission\n"); }#endif return 0;}} // namespace access_

在Linux下的执行结果如下:

GitHub:https://github.com//fengbingchun/Messy_Test

“C语言中access/_access函数的用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


分享名称:C语言中access/_access函数的用法
分享URL:http://bzwzjz.com/article/jidogg.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: H5网站制作 响应式网站设计 成都营销网站建设 网站建设 定制网站制作 成都网站建设 响应式网站建设 成都网站设计 成都网站建设 教育网站设计方案 成都网站设计 营销型网站建设 成都网站建设 网站设计 四川成都网站设计 高端网站设计 专业网站设计 重庆网站建设 成都网站设计 成都网站制作 成都网站制作 广安网站设计