_getcwd, _wgetcwd

取得目前工作目錄。

語法

char *_getcwd(
   char *buffer,
   int maxlen
);
wchar_t *_wgetcwd(
   wchar_t *buffer,
   int maxlen
);

參數

buffer
路徑的儲存位置。

maxlen
路徑的最大長度 (以字元為單位):char_getcwd,以及 wchar_t_wgetcwd

傳回值

傳回 buffer的指標。 傳 NULL 回值表示錯誤,並將 ENOMEMerrno 設定為 ,表示記憶體不足而無法配置 maxlen 位元組(當 NULL 引數指定為 buffer 時),或 設定為 ERANGE ,表示路徑長度超過 maxlen 字元。 如果 maxlen 小於或等於零,此函式會叫用不正確參數處理常式,如參數驗證 中所述

如需這些傳回碼和其他傳回碼的詳細資訊,請參閱 errno_sys_errlist_doserrno_sys_nerr

備註

_getcwd 函式會取得預設磁碟機之目前工作目錄的完整路徑,並將其儲存在 buffer。 整數引數 maxlen 指定該路徑的最大長度。 如果路徑長度 (包括結束的 null 字元) 超過 maxlenbuffer 引數可以是 NULL;系統會使用 maxlen 自動配置大小至少為 malloc的緩衝區 (並只在必要時才增加) 來儲存路徑。 這個緩衝區稍後可以藉由呼叫 free ,並對其傳遞 _getcwd 傳回值 (已配置緩衝區的指標) 來釋放。

_getcwd 會傳回代表目前工作目錄路徑的字串。 如果目前的工作目錄是根目錄,字串會以反斜線結尾( \ )。 如果目前的工作目錄是根目錄以外的目錄,字串會以目錄名稱結尾,而不是反斜線。

_wgetcwd_getcwd的寬字元版本, buffer 引數與 _wgetcwd 的傳回值是寬字元字串。 否則,_wgetcwd_getcwd 的行為即會相同。

定義 和 _CRTDBG_MAP_ALLOC_DEBUG ,呼叫 和 _wgetcwd 會由 和 _wgetcwd_dbg 的呼叫 _getcwd_getcwd_dbg 取代,讓您偵錯記憶體配置。 如需詳細資訊,請參閱 _getcwd_dbg_wgetcwd_dbg

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

泛型文字常式對應

Tchar.h 常規 _UNICODE_MBCS 未定義 _MBCS 定義 _UNICODE 定義
_tgetcwd _getcwd _getcwd _wgetcwd

需求

常式 必要的標頭
_getcwd <direct.h>
_wgetcwd <direct.h><wchar.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_getcwd.c
// Compile with: cl /W4 crt_getcwd.c
// This program places the name of the current directory in the
// buffer array, then displays the name of the current directory
// on the screen. Passing NULL as the buffer forces getcwd to allocate
// memory for the path, which allows the code to support file paths
// longer than _MAX_PATH, which are supported by NTFS.

#include <direct.h> // _getcwd
#include <stdlib.h> // free, perror
#include <stdio.h>  // printf
#include <string.h> // strlen

int main( void )
{
   char* buffer;

   // Get the current working directory:
   if ( (buffer = _getcwd( NULL, 0 )) == NULL )
      perror( "_getcwd error" );
   else
   {
      printf( "%s \nLength: %zu\n", buffer, strlen(buffer) );
      free(buffer);
   }
}
C:\Code

另請參閱

目錄控制項
_chdir, _wchdir
_mkdir, _wmkdir
_rmdir, _wrmdir