linux提供了函数getcwd,用于提供当前程序的路径:
#include<unistd.h>
char *getcwd(char *buf,size_t size);
buf:用于存储路径的空间,size是buf的长度
#include <unistd.h>
#include <iostream>
using namespace std;
int main()
{
char buff[200] = {0};
char* path = getcwd(buff, sizeof(buff));
if(path != nullptr)
{
cout<<buff<<endl;
cout<<path<<endl;
cout<<(void*)buff<<" "<<(void*)path<<endl;
}
else
{
cout<<"size of buff is not enough"<<endl;
}
return 0;
}
当buff的空间足够时,getcwd会将路径保存在buff中,返回值也指向buff
当buff的空间不够时,getcwd会返回nullptr,errno会被设置为ERANGE
getcwd还有另外一种使用方式,就是buf传入nullptr,size传入0,那么他会自己分配一个空间用于保存目录,需要程序在在面对其进行释放: