變更目前目錄
使用中路徑結尾的目錄稱為目前目錄;這是使用中應用程式啟動所在的目錄,除非它已明確變更。 應用程式可以呼叫 getCurrentDirectory函式,判斷哪個目錄是目前的目錄。 有時必須使用 GetFullPathName 函式來確保應用程式需要時會包含驅動器號。
注意
雖然每個進程只能有一個目前目錄,但如果應用程式使用 SetCurrentDirectory 函式切換磁碟區,系統就會記住每個磁碟區的最後一個目前路徑(驅動器號)。 只有在將目前目錄的參考點變更為不同的磁碟區並指定沒有完整路徑的驅動器號的情況下,此行為才會出現。 這適用於 Get 或 Set 操作。
應用程式可以呼叫 SetCurrentDirectory 函式來變更目前目錄。
下列範例示範如何使用 GetCurrentDirectory 和 SetCurrentDirectory。
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#define BUFSIZE MAX_PATH
void _tmain(int argc, TCHAR **argv)
{
TCHAR Buffer[BUFSIZE];
DWORD dwRet;
if(argc != 2)
{
_tprintf(TEXT("Usage: %s <dir>\n"), argv[0]);
return;
}
dwRet = GetCurrentDirectory(BUFSIZE, Buffer);
if( dwRet == 0 )
{
printf("GetCurrentDirectory failed (%d)\n", GetLastError());
return;
}
if(dwRet > BUFSIZE)
{
printf("Buffer too small; need %d characters\n", dwRet);
return;
}
if( !SetCurrentDirectory(argv[1]))
{
printf("SetCurrentDirectory failed (%d)\n", GetLastError());
return;
}
_tprintf(TEXT("Set current directory to %s\n"), argv[1]);
if( !SetCurrentDirectory(Buffer) )
{
printf("SetCurrentDirectory failed (%d)\n", GetLastError());
return;
}
_tprintf(TEXT("Restored previous directory (%s)\n"), Buffer);
}