為了處理跨平臺兼容性,getcwd
函數在不同的操作系統中可能有不同的實現。在C++中,你可以使用標準庫中的<filesystem>
頭文件,它提供了一個跨平臺的current_path
函數,可以用來獲取當前工作目錄。
以下是一個簡單的示例:
#include <iostream>
#include <filesystem>
int main() {
try {
std::filesystem::path current_path = std::filesystem::current_path();
std::cout << "Current working directory: " << current_path << std::endl;
} catch (const std::filesystem::filesystem_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
這個示例使用了C++17的<filesystem>
庫,它提供了一個跨平臺的API來處理文件系統操作。current_path
函數返回一個std::filesystem::path
對象,表示當前工作目錄。如果在獲取當前工作目錄時發生錯誤,將拋出std::filesystem::filesystem_error
異常。
請注意,為了使這個示例正常工作,你需要確保你的編譯器支持C++17標準,并在編譯時啟用C++17支持。例如,如果你使用的是g++編譯器,可以使用以下命令行選項來啟用C++17:
g++ -std=c++17 -o my_program my_program.cpp