1. 程式人生 > >C++設定和獲取當前工作路徑

C++設定和獲取當前工作路徑

通常,你在服務程式中呼叫DLL,而DLL又會載入許多配置和檔案,一般會出現DLL載入不到配置和檔案,原因是你的服務程式被載入後,路徑並不是你程式的所在目錄,故DLL也不是,因此載入不了。解決辦法,是在DLL的路徑或服務程式中設計當前的工作路徑。

主要函式為:SetCurrentDirectory;

設定當前工作路徑例項如下:

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

int main()
{
 char buf[1000];
 int i=1000;

 GetCurrentDirectory(1000,buf);  //得到當前工作路徑

 cout<<buf<<endl;

 char strModule[256];
 GetModuleFileName(NULL,strModule, 256); //得到當前模組路徑

 cout<<strModule<<endl;

 string a;
  a.assign(buf);
 cout<<a<<endl;
  a.append("
//..//");     //設定為當前工作路徑為當時的上一級

 //a=a+"..//";
 SetCurrentDirectory(a.c_str());  //設定

 GetCurrentDirectory(1000,buf);
 cout<<buf<<endl;

 return 0;
}