Find out the current working directory in C/C++


在本部分中,我們將會學習如何使用 C 或 C++ 獲取當前工作目錄。我們為當前作業系統定義了一些標誌。

示例程式碼

即時演示

#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

#include<iostream>
using namespace std;

std::string get_current_dir() {
   char buff[FILENAME_MAX]; //create string buffer to hold path
   GetCurrentDir( buff, FILENAME_MAX );
   string current_working_dir(buff);
   return current_working_dir;
}

main() {
   cout << get_current_dir() << endl;
}

輸出

D:\C++ Programs\section 53

更新於:2019 年 7 月 30 日

6,000+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告