更改当前目录

活动路径末尾的目录称为当前目录;它是活动应用程序启动的目录,除非已显式更改。 应用程序可以通过调用 GetCurrentDirectory 函数来确定当前目录。 有时需要使用 GetFullPathName 函数来确保在应用程序需要时包含驱动器号。

注意

尽管每个进程只能有一个当前目录,但如果应用程序使用 SetCurrentDirectory 函数切换卷,系统会记住每个卷 (驱动器号) 的最后一个当前路径。 仅在将当前目录引用点更改为不同卷时指定没有完全限定路径的驱动器号时,此行为才会显现出来。 这适用于“获取”或“设置”操作。

 

应用程序可以通过调用 SetCurrentDirectory 函数来更改当前目录。

以下示例演示如何使用 GetCurrentDirectorySetCurrentDirectory

#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);
}