mac和Linux的方法是一样的,但是和windows有差异,如果要写出既可以在windows运行,又可以在Linux运行的代码,则需要增加代码宏控设置,判断不同的平台使用不同的代码,可以参考这篇文章:c/c++判断当前操作系统类型
mac、Linux
#include "iostream"
#include <unistd.h>
using namespace std;
int main(int argc, char** argv)
{
const int MAXPATH=250;
char buffer[MAXPATH];
getcwd(buffer, MAXPATH);
printf("The current directory is: %s", buffer);
}
windows
#include <stdio.h>
#include <direct.h>
int main()
{
const int MAXPATH = 250;
char buffer[MAXPATH];
getcwd(buffer, MAXPATH);
printf("The current directory is: %s", buffer);
}
兼容mac 、Linux、Windows的写法
#include <iostream>
#ifdef _WIN32
#include <direct.h>
#elif __APPLE__ || __linux__
#include<unistd.h>
#endif
using namespace std;
int main(int argc, char** argv)
{
char runPath[1024] = {0};
getcwd(runPath, sizeof(runPath));
cout << runPath << endl;
}
- 代码运行截图: