獲取當前執行程式路徑

2021-07-11 22:25:59 字數 2595 閱讀 4333

vc上或取當前路徑有多種方法,最常用的是使用 getcurrentdirectory和getmodulefilename函式,個中都有諸多注意事項,特別總結一下。

1、使用getcurrentdirectory函式

假設程式路徑為d:\test\tst.exe,執行getcurrentdirectory函式

char pbuf[max_path];

getcurrentdirectory(max_path,pbuf);

pbuf="d:\test"

但是如果使用cfiledialog、cfile::open等函式後,設定不當則會導致再次獲取當前路徑值改變。所以,如要避免當前路徑改變,如果使用cfiledialog,則要把在cfiledialog的dwflags標誌設定為ofn_nochangedir。如下:

cfiledialog hfiledlg(false,null ,

null,

ofn_filemustexist | ofn_readonly | ofn_pathmustexist | ofn_nochangedir,

text("text files (*.txt)|*.txt|all files(*.*)|*.*|"),

null);

也可以,先執行getcurrentdirectory把獲取到目錄路徑儲存下來,處理完成後,再次setcurrentdirectory設定一下。

2、使用getmodulefilename

cstring strcurpath;

getmodulefilename(null,strcurpath.getbuffer(max_path),max_path);

int pos= strcurpath.reversefind(_t('\\'));

strcurpath = strcurpath.left(pos);

輸出(路徑包括執行檔名):

strcurpath="d:\test\tst.exe"

通過對話方塊開啟檔案時,一般均需獲取開啟檔案的完整路徑,可使用cfiledialog的getpathname函式,**如下:

cfiledialog hfiledlg(false,null ,

null,

ofn_filemustexist | ofn_readonly | ofn_pathmustexist | ofn_nochangedir,

text("text files (*.txt)|*.txt|all files(*.*)|*.*|"),

null);

if(hfiledlg.domodal() == idok)

通過getmodulefilename獲取完整路徑後,可以使用pathstrippath api函式解析路徑,**示例如下:

/*

#include "shlwapi.h"

#pragma comment(lib, "shlwapi.lib ")

*/tchar szpath2 = text("d:\\test\\tst.exe");

pathstrippath(szpath2);

// result: szpath2 ==tst.exe

tchar szpath3 = text("d:\\test\\debug");

pathstrippath(szpath3);

// result: szpath3 == debug

tchar szpath4 = text("d:\\test\\debug\\");

pathstrippath(szpath4);

// result: szpath4 == debug\

tchar szpath5 = text("d:\\");

pathstrippath(szpath5);

// result: szpath5 == d:\

使用此函式要注意,並非只是提取檔名,如果它不能識別時,則會返回原始字串(不做處理)。所以,不放心的話,自己手動提取檔名更為保險。

golang獲取當前執行程式的路徑

背景 linux golang 在程式執行中,經常需要讀取檔案,如果檔案路徑寫成絕對路勁,對於程式移植到其他機器上執行時,可能會出錯,找不到檔案。所以,最好的方式是寫成相對路徑。實現方式 假設有如下檔案路徑 test main.go api testapi.gopackage package imp...

可執行程式當前路徑

cstring spath getmodulefilename null,spath.getbuffersetlength max path 1 max path spath.releasebuffer int npos npos spath.reversefind spath spath.left...

獲取本執行程式所在的當前路徑

1.獲取和設定當前目錄的完全限定路徑。string str system.environment.currentdirectory result c 3.獲取新的 process 元件並將其與當前活動的程序關聯的主模組的完整路徑,包含檔名。string str system.diagnostics....