c++ - 获取当前目录的跨平台方式是什么?

标签 c++ cross-platform getcwd

我需要一种跨平台的方式来获取当前的工作目录(是的,getcwd 可以满足我的需求)。我认为这可能会奏效:

#ifdef _WIN32
    #include <direct.h>
    #define getcwd _getcwd // stupid MSFT "deprecation" warning
#elif
    #include <unistd.h>
#endif
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string s_cwd(getcwd(NULL,0));
    cout << "CWD is: " << s_cwd << endl;
}

我得到了这个读数:

应该没有内存泄漏,它应该也可以在 Mac 上运行,对吗?

更新:我担心这里仍然有问题(我试图避免创建具有确定长度的 char 数组,因为没有适当的方法来为 getcwd 获得合适的长度):

char* a_cwd = getcwd(NULL,0);
string s_cwd(a_cwd);
free(a_cwd); // or delete a_cwd? 

最佳答案

如果您可以加入,请使用 boost filesystem方便的跨平台文件系统操作。

boost::filesystem::path full_path( boost::filesystem::current_path() );

这里是 example .

编辑:正如 Roi Danton 在评论中指出的那样,文件系统成为 ISO C++ in C++17 的一部分,因此不再需要提升:

std::filesystem::current_path();

关于c++ - 获取当前目录的跨平台方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868680/

相关文章:

python - 如何找到脚本的目录?

c++ - C、Linux、getcwd/chdir() : get binary path

c++ - hello world 在 gcc 5.3.0/bin/ld : invalid option -- 'p' 上失败

c++ - 用 g++ 编译的奇怪代码

android - 适用于 iPhone 和 Android 的跨平台且性能良好的移动应用程序

java - 跨平台方式监听 USB 连接?

python - 通过符号链接(symbolic link)启动 python 脚本

c++ - Boost Python没有为std::string找到to_python转换器

c++ - C++ 中的彩色输出

c++ - 什么属于教育工具来证明人们在 C/C++ 中做出的无根据的假设?