效果
源碼
#include
#include
int main(int argc, PCHAR argv[]){
//當(dāng)前路徑
CHAR szCurrentDirectory[MAX_PATH];
//模塊路徑
CHAR szModulePath[MAX_PATH];
//Kernel32文件名
LPTSTR szKernel32 = TEXT("Kernel32.dll");
//Kernel32句柄
HMODULE hKernel32;
//當(dāng)前路徑長(zhǎng)度,也用來判斷是否成功
DWORD dwCurDirPathLen;
//獲取進(jìn)程當(dāng)前目錄
dwCurDirPathLen = GetCurrentDirectory(MAX_PATH, szCurrentDirectory);
if (dwCurDirPathLen == 0){
printf("獲取進(jìn)程當(dāng)前目錄錯(cuò)誤: %d\n", GetLastError());
return 1;
}
printf("當(dāng)前進(jìn)程的目錄為: %s\n", szCurrentDirectory);
//將進(jìn)程當(dāng)前目錄設(shè)置為 "C:\" ,這樣如果用相對(duì)路徑創(chuàng)建目錄則會(huì)創(chuàng)建到C盤去
lstrcpy(szCurrentDirectory, TEXT("C:\\"));
if (!SetCurrentDirectory(szCurrentDirectory)){
printf("設(shè)置當(dāng)前目錄錯(cuò)誤: %d\n", GetLastError());
return 2;
}
printf("已設(shè)置當(dāng)前目錄為 %s\n", szCurrentDirectory);
//在當(dāng)前目錄下創(chuàng)建 "子目錄" 目錄
CreateDirectory(TEXT("子目錄"), NULL);
//再次獲取進(jìn)程當(dāng)前目錄
dwCurDirPathLen = GetCurrentDirectory(MAX_PATH, szCurrentDirectory);
if (dwCurDirPathLen == 0){
printf("獲取進(jìn)程當(dāng)前目錄錯(cuò)誤: %d\n", GetLastError());
return 3;
}
printf("GetCurrentDirectory獲取當(dāng)前進(jìn)程的目錄為: %s\n", szCurrentDirectory);
//使用NULL參數(shù)獲取本模塊路徑
if (!GetModuleFileName(NULL, szModulePath, MAX_PATH)){
printf("獲取模塊路徑錯(cuò)誤: %d\n", GetLastError());
return 4;
}
printf("本模塊路徑為: %s\n", szModulePath);
//獲取Kernel32.dll的模塊句柄
hKernel32 = LoadLibrary(szKernel32);
//使用Kernel32.dll模塊句柄獲取其路徑
if (!GetModuleFileName(hKernel32, szModulePath, MAX_PATH)){
printf("獲取模塊路徑錯(cuò)誤: %d\n", GetLastError());
return 5;
}
printf("Kernel32.dll模塊路徑為: %s\n", szModulePath);
getchar();
return 0;
}