C++ 獲取當(dāng)前目錄

1. 說(shuō)明

  1. 如果編譯器支持C++17,則建議使用std::filesystem::current_path
  2. 如果只在windows平臺(tái)使用,可使用_getcwd
  3. 如果只在linux平臺(tái)使用,可使用getcwd
  4. 如果代碼要跨平臺(tái)使用,可以使用通過(guò)編譯統(tǒng)一的版本

2. C++17 std::filesystem::current_path

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    std::cout << "Current working directory: " << fs::current_path() << '\n'; 
}
Current working directory:  "D:/local/ConsoleApplication1"

std::filesystem::current_path 還可以改變當(dāng)前目錄
https://en.cppreference.com/w/cpp/filesystem/current_path

3. windows平臺(tái) _getcwd

#include <direct.h>

std::string current_working_directory()
{
    char buff[250];
    _getcwd(buff, 250); 
    std::string current_working_directory(buff);
    return current_working_directory;
}

int main()
{
    std::cout << "Current working directory: " << current_working_directory() << endl;
}

直接使用getcwd會(huì)有告警
https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getcwd-wgetcwd?view=msvc-160

4. linux平臺(tái) getcwd

#include <unistd.h>

int main() 
{
    char buff[250];
    getcwd(buff, 250);
    string current_working_directory(buff);
    cout << "Current working directory: " << current_working_directory<< endl;

    return 0;
}

或者使用get_current_dir_name

#include <unistd.h>

int main() 
{
    char *cwd = get_current_dir_name();
    cout << "Current working directory: " << cwd << endl;
    free(cwd);

    return 0;
}

https://man7.org/linux/man-pages/man3/getcwd.3.html
https://linux.die.net/man/3/get_current_dir_name

5. 通過(guò)編譯宏統(tǒng)一兩者版本

參考: https://www.tutorialspoint.com/find-out-the-current-working-directory-in-c-cplusplus

#if defined(_MSC_VER)
    #include <direct.h>
    #define GetCurrentDir _getcwd
#elif defined(__unix__)
    #include <unistd.h>
    #define GetCurrentDir getcwd
#else
#endif

std::string get_current_directory() 
{
    char buff[250]; 
    GetCurrentDir(buff, 250);
    string current_working_directory(buff);
    return current_working_directory;
}

int main(int argc, char* argv[])
{
    std::cout << "Current working directory: " << get_current_directory() << endl;
    
    return 0;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容