Linux C/C++ 获取当前工作目录

在windows系统下,getcwd()函数是在#include <direct.h>;
Linux系统,则是在#include <unistd.h>。

1、getcwd()

char *getcwd(char buf, size_t size);
参数
buf:保存当前目录的缓冲区
参数size:在现代linux 中,buf 的长度至少可以为255 字节
返回值:成功返回指向当前目录的指针,和buf 的值一样,错误返回NULL。
普通用法:

#include <unistd.h>
#include <iostream>
using namespace std;
#define PATH_SIZE 255
int main(void)
{
	char path[PATH_SIZE];
	if(!getcwd(path,PATH_SIZE)){
		cout<<"Get path fail!"<<endl;
		return 0;
	}
	cout<<"path:"<<path<<endl;
  return 0;
}

这样会将工作目录的绝对路径复制到buf所指向的空间中,但如果路径长度大于size,则会返回NULL,错误代码为ERANGE.所以我们在定义path的时候得定义的足够大,但这样又会使得内存浪费,Linux的文件名长度限制为255个英文字符,理论上绝对路径的大小应该可以足够大,故而这样使用总有返回NULL的时候,所以getcwd()个我们提供了下面的一种用法:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <iostream>
using namespace std;
int main(void)
{
  char *path = NULL;
  path = getcwd(NULL,0);
  puts(path);
  free(path);
	cout<<"size:"<<sizeof(path)<<endl;//查看path占用了多少字节
  return 0;
}

可以采取令 buf 为 NULL并使 size 为零来使 getcwd 调用 malloc 动态给 buf 分配,但是这种情况要特别注意使用后释放缓冲以防止内存泄漏。

2、get_current_dir_name()

getcwd()函数需要考虑缓冲区占用字节大小,比较麻烦。get_current_dir_name()函数可以更便捷,其用法如下:
char *get_current_dir_name(void);
–参数:无
–返回值:成功返回指向当前目录的指针,错误返回NULL。

#include <unistd.h>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
   char *path;
   path = get_current_dir_name();
   cout<<"path:"<<path<<endl;
 return 0;
}

PS:获取到的是可执行文件所在的位置。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章