溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C語言中access/_access函數的使用實例詳解

發(fā)布時間:2020-08-27 10:45:16 來源:腳本之家 閱讀:201 作者:fengbingchun 欄目:編程語言

在Linux下,access函數的聲明在<unistd.h>文件中,聲明如下:

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

access函數用來判斷指定的文件或目錄是否存在(F_OK),已存在的文件或目錄是否有可讀(R_OK)、可寫(W_OK)、可執(zhí)行(X_OK)權限。F_OK、R_OK、W_OK、X_OK這四種方式通過access函數中的第二個參數mode指定。如果指定的方式有效,則此函數返回0,否則返回-1。

在Windows下沒有access函數,但在<io.h>文件中有_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 <iostream>
#include <vector>
#include <string>
#ifdef _MSC_VER
#include <io.h>
#else
#include <unistd.h>
#endif
namespace access_ {
int test_access_1()
{
#ifdef _MSC_VER
 const std::string path{ "E:/GitCode/Messy_Test/" };
 const std::vector<const std::string> 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<const char*> 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下的執(zhí)行結果如下:

C語言中access/_access函數的使用實例詳解

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

總結

以上所述是小編給大家介紹的C語言中access/_access函數的使用實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI