_getcwd_wgetcwd

获取当前工作目录。

语法

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

参数

buffer
路径的存储位置。

maxlen
路径的最大长度(以字符为单位):char_getcwdwchar_t_wgetcwd

返回值

返回指向 buffer的指针。 NULL 返回值指示错误,并将 errno 设置为 ENOMEM,指示内存不足,无法分配 maxlen 个字节(当将 NULL 参数给定为 buffer时),或设置为 ERANGE,指示该路径长于 maxlen 个字符。 如果 maxlen 小于或等于零,此函数将调用无效的参数处理程序,如参数验证中所述。

有关这些和其他的返回代码的详细信息,请参阅 errno_doserrno_sys_errlist_sys_nerr

备注

_getcwd 函数获取默认驱动器的当前工作目录的完整路径,并将其存储在 buffer中。 整数参数 maxlen 指定路径的最大长度。 如果路径的长度(包括终止 null 字符)超过 maxlen,则会发生错误。 buffer 参数可为 NULL;使用 malloc 自动分配大小至少为 maxlen(仅在必需时超过)的缓冲区,以存储路径。 之后可通过调用 free 并向其传递 _getcwd 返回值(指向已分配缓冲区的指针)来释放此缓冲区。

_getcwd 返回一个字符串,它表示当前工作目录的路径。 如果当前工作目录为根目录,则字符串以反斜杠 (\) 结尾。 如果当前工作目录为根目录之外的目录,则字符串以目录名称结尾,而不是以反斜杠结尾。

_wgetcwd_getcwd的宽字符版本; buffer 参数和 _wgetcwd 的返回值都是宽字符字符串。 除此以外,_wgetcwd_getcwd 的行为完全相同。

定义 _DEBUG_CRTDBG_MAP_ALLOC 时,对 _getcwd_wgetcwd 的调用将替换为对 _getcwd_dbg_wgetcwd_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