在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:獲取到的是可執行文件所在的位置。