溫馨提示×

C++ getcwd在不同系統上的表現

c++
小樊
114
2024-11-27 16:32:16
欄目: 編程語言

getcwd 是 C++ 標準庫中的一個函數,用于獲取當前工作目錄的絕對路徑

  1. Linux 和 macOS: 在 Linux 和 macOS 系統上,getcwd 的行為通常是一致的。它接受一個字符數組(通常是足夠大的以容納完整路徑)作為參數,并返回該數組的內容,表示當前工作目錄的絕對路徑。如果發生錯誤(例如,提供的緩沖區太?。?,getcwd 將返回 nullptr,并設置 errno。

示例代碼:

#include <iostream>
#include <cstdio>
#include <cstring>

int main() {
    char cwd[1024];
    if (getcwd(cwd, sizeof(cwd)) != nullptr) {
        std::cout << "Current working directory: " << cwd << std::endl;
    } else {
        std::cerr << "Error getting current working directory" << std::endl;
    }
    return 0;
}
  1. Windows: 在 Windows 系統上,getcwd 的行為與 Linux 和 macOS 類似。它同樣接受一個字符數組作為參數,并返回該數組的內容,表示當前工作目錄的絕對路徑。如果發生錯誤(例如,提供的緩沖區太?。?,getcwd 將返回 nullptr,并設置 errno。

示例代碼:

#include <iostream>
#include <cstdio>
#include <cstring>

int main() {
    char cwd[1024];
    if (getcwd(cwd, sizeof(cwd)) != nullptr) {
        std::cout << "Current working directory: " << cwd << std::endl;
    } else {
        std::cerr << "Error getting current working directory" << std::endl;
    }
    return 0;
}

盡管 getcwd 在不同操作系統上的行為基本一致,但在實際使用中,仍需注意一些差異,例如路徑分隔符和文件系統類型。為了編寫可移植的代碼,可以使用跨平臺庫(如 Boost.Filesystem)來處理文件路徑。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女