更改 C 中的當前工作目錄
處理文件和 I/O 時經常遇到需要調整當前工作目錄的情況運作。 C 透過使用 std::filesystem::current_path 函數為此任務提供了一個獨立於平台的解決方案。
C 17 解決方案:std::filesystem::current_path
在C 17中,std::filesystem庫為檔案系統操作提供了跨平台API。 std::filesystem::current_path 函數允許檢索和設定目前工作目錄。
範例:
#include
int main() {
namespace fs = std::filesystem;
// Retrieve the current working directory
fs::path current_path = fs::current_path();
// Set the current working directory
fs::current_path(current_path / "new_directory");
}
在此範例中,我們首先使用 current_path 函數檢索目前工作目錄並將其儲存在 fs::path 物件中。然後我們可以使用這個 fs::path 物件將目前工作目錄設定為新路徑,在本例中為子目錄「new_directory」。
Compatibility
std::filesystem 庫在 C 17 及更高版本中可用。對於舊版的 C ,可以使用特定於平台的選項,例如 Windows 的 direct.h 或用於 UNIX/POSIX 系統的 unistd.h 。但是,這些選項缺乏 std::filesystem::current_path.
的可移植性免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3