getcwd()
是一個 C++ 標準庫函數,用于獲取當前工作目錄的路徑
getcwd()
的返回值:如果它返回一個空指針,說明獲取目錄失敗。此時,可以通過檢查 errno
來獲取更多關于錯誤的信息。#include <iostream>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
std::cout << "Current working directory: " << cwd << std::endl;
} else {
std::cerr << "Error getting current working directory: " << std::strerror(errno) << std::endl;
}
return 0;
}
access()
函數檢查當前用戶是否具有訪問目標目錄的權限:#include <iostream>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
std::cout << "Current working directory: " << cwd << std::endl;
if (access(cwd, R_OK) == 0) {
std::cout << "You have read and write access to the current working directory." << std::endl;
} else {
std::cerr << "You do not have read and write access to the current working directory. Error: " << std::strerror(errno) << std::endl;
}
} else {
std::cerr << "Error getting current working directory: " << std::strerror(errno) << std::endl;
}
return 0;
}
sudo
命令提升權限,然后再次嘗試運行程序。請注意,這些方法僅適用于處理文件和目錄的讀取和寫入權限。如果你需要處理其他類型的權限問題,請根據具體情況采取相應的措施。