關於檔案路徑操作的2個函式

2021-04-12 22:57:56 字數 2225 閱讀 5332

做程式,經常會和各種檔案的路徑打交道。相關的api也很多。但有幾點要注意的。

1。dword getcurrentdirectory(

dwordnbufferlength

,// size of directory buffer

lptstrlpbuffer

// directory buffer

);

這個api函式大家不陌生吧。我以前經常用這個函式來取得當前程式的目錄。但是,這個函式,得到的是當前程序的活動目錄。並不一定是程式exe檔案的目錄。很多操作,都會影響該函式取得的值。

比如,程式開始後,開啟過某個檔案,或者選擇過某個路徑,都會影響到currentdirectory。所以,想要取得exe檔案所在的目錄,最好使用下面的函式:

dword getmodulefilename(

hmodulehmodule

,// handle to modulelptstrlpfilename

,// path bufferdwordnsize

// size of buffer);

這個api可以得到exe的路徑。但得到的路徑中,包括了exe檔案本身。比如,程式在c:/test/win32.exe,那麼得到的路徑,會包含"win32.exe"檔名在內。我們可以使用另乙個api去掉路徑中的檔名。
bool pathremovefilespec(lptstrpszpath);removes the trailing file name and backslash from a path, if it has them. 

需要注意的是,這個api需要引用下面的庫。

header:declared in shlwapi.h.

import library:shlwapi.lib.

這樣,得到的當前路徑,就很保險。

2。bool createdirectory(lpctstrlppathname

,// directory name

lpsecurity_attributeslpsecurityattributes

// sd);

關於這個api,可以用來建立路徑。或者說建立資料夾。
但有一點要注意,建立的路徑,不能是多重路徑。也就是說,該函式只能建立已存在的路徑下的一級路徑。
舉個例子:
若c:/test 已經存在。如果呼叫該api:
cstring strtemppath = "c://test//123";
createdirectory(strtemppath,null);
則可以成功在c:/test 下建立123資料夾。
但如果
cstring strtemppath = "c://test//321//123";
createdirectory(strtemppath,null);
則建立失敗!
因為,c:/test/321這個路徑並不存在。createdirectory只能建立一層路徑。
所以,要先建立c:/test/321,再建立c:/test/321/123
cstring strtemppath = "c://test//321";
createdirectory(strtemppath,null);
strtemppath = "c://test//321//123";
createdirectory(strtemppath,null);
這樣,就可以了。

C 常用的檔案操作路徑函式

shlwapi.dll中的實用api函式發布 在windows system目錄下有這個動態鏈結庫 bool pathfileexists lpctstr lpszpath 功能 檢查檔案 路徑是否存在 lptstr pathfindfilename lpctstr ppath 功能 獲得路徑中的檔...

關於檔案操作的API函式

在vc中,大多數情況對檔案的操作都使用系統提供的 api 函式,但有的函式我們不是很熟悉,以下提供一些檔案操作 api 函式介紹 一般檔案操作 api createfile 開啟檔案 要對檔案進行讀寫等操作,首先必須獲得檔案控制代碼,通過該函式可以獲得檔案控制代碼,該函式是通向檔案世界的大門。rea...

常見檔案 目錄 路徑操作函式

bool winapi deletefile in lpctstr lpfilename 刪除乙個檔案 int shfileoperation lpshfileopstruct lpfileop 刪除很多檔案 bool winapi removedirectory in lpctstr lppath...