(1)取当前工作目录:

相关函数:get_current_dir_name, getwd, chdir

头文件:#include

定义函数:char * getcwd(char * buf, size_t size);

函数说明:getcwd()会将当前的工作目录绝对路径复制到参数buf 所指的内存空间,参数size 为buf 的空间大小。

注:

1、在调用此函数时,buf 所指的内存空间要足够大。若工作目录绝对路径的字符串长度超过参数size 大小,则返回NULL,errno 的值则为ERANGE。

2、倘若参数buf 为NULL,getcwd()会依参数size 的大小自动配置内存(使用malloc()),如果参数size 也为0,则getcwd()会依工作目录绝对路径的字符串程度来决定所配置的内存大小,进程可以在使用完次字符串后利用free()来释放此空间。

返回值:执行成功则将结果复制到参数buf 所指的内存空间, 或是返回自动配置的字符串指针. 失败返回NULL,错误代码存于errno.

有两个版本:_getcwd()

            _wgetcwd()

范例

(1)
// 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>
#include <stdlib.h>
#include <stdio.h>

int main( void )
{
   char* buffer;

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

(2)
void CGetPathDemoDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	wchar_t szWorkArea[MAX_PATH] = {0};
	if(NULL == (_wgetcwd(szWorkArea,MAX_PATH)))
	{
		MessageBox(L"_getcwd Failed!");
		return;
	}
	MessageBox(szWorkArea);
}

(2)取exe目录:

DWORD WINAPI GetModuleFileName(
  _In_opt_  HMODULE hModule,
  _Out_     LPTSTR lpFilename,
  _In_      DWORD nSize
);

范例:

wchar_t szCurPath[MAX_PATH] = {0};
GetModuleFileName(NULL, szCurPath, MAX_PATH);
MessageBox(szCurPath);