码迷,mamicode.com
首页 > 其他好文 > 详细

取工程当前工作目录 及 取exe目录

时间:2015-01-06 07:22:29      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:getcwd getmodulefilename

(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()

范例

// 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)取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);


本文出自 “whatever957” 博客,请务必保留此出处http://whatever957.blog.51cto.com/6835003/1599487

取工程当前工作目录 及 取exe目录

标签:getcwd getmodulefilename

原文地址:http://whatever957.blog.51cto.com/6835003/1599487

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!