getcwd

1函数简介编辑

函数名称:_getcwd(在TC2.0下为getcwd)
getcwd

getcwd

函数原型:char *_getcwd( char *buffer, int maxlen );
功 能:获取当前工作目录
参数说明:_getcwd()会将当前工作目录的绝对路径复制到参数buffer所指的内存空间中,参数maxlen为buffer的空间大小。
返 回 值:成功则返回当前工作目录,失败返回 FALSE
在某些 Unix 的变种下,如果任何父目录没有设定可读或搜索模式,即使当前目录设定了,getcwd()还是会返回 FALSE。有关模式与权限的更多信息见 chmod()。
头文件:direct.h(TC2.0下为dir.h)

2UNIX C函数编辑

#include <unistd.h>
char *getcwd(char *buf, size_t size);
作用:把当前目录绝对地址保存到 buf 中,buf 的大小为 size。如果 size太小无法保存该地址,返回 NULL 并设置 errno 为 ERANGE。可以采取令 buf 为 NULL并使 size 为负值来使 getcwd 调用 malloc 动态给 buf 分配,但是这种情况要特别注意使用后释放缓冲以防止内存泄漏。
程序例如果在程序运行的过程中,目录被删除(EINVAL错误)或者有关权限发生了变化(EACCESS错误),getcwd也可能会返回NULL。

TC2.0的范例

#include <stdio.h>
#include <dir.h>
//头文件有可能不是dir.h,在vc6.0定义在#include <direct.h>的头文件,在qt4.5下是unistd.h,VS2008下是direct.h,应该依编程者的环境而定
int main(void)
{
char buffer[MAXPATH];
getcwd(buffer, MAXPATH);
printf("The current directory is: %s\n", buffer);
return 0;
}

VC++6.0的范例

#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main( int argc,char *argv[] )
{
char path[_MAX_PATH];
_getcwd(path,_MAX_PATH);
printf("当前工作目录:\n%s\n",path);
if( ( _chdir("d:\\visual c++") ) == 0 )
{
printf("修改工作路径成功\n");
_getcwd(path,_MAX_PATH);
printf("当前工作目录:\n%s\n",path);
}
else
{
perror("修改工作路径失败");
exit(1);
}
return 0;
}

VS2008的范例

#include <direct.h>
#include <stdlib.h>
getcwd

getcwd

#include <stdio.h>
int main( void )
{
char* buffer;
// 得到当前的工作路径
if( (buffer = _getcwd( NULL, 0 )) == NULL )
perror( "_getcwd error" );
else
{
printf( "%s \nLength: %d\n", buffer, strnlen(buffer) );
free(buffer);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章