什么是跨平台的方式来获取当前目录? [英] What is a cross-platform way to get the current directory?

查看:152
本文介绍了什么是跨平台的方式来获取当前目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个跨平台的方式来获取当前的工作目录(是的,getcwd做我想要的)。我认为这可能会诀窍:

I need a cross-platform way to get the current working directory (yes, getcwd does what I want). I thought this might do the trick:

#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;
}

我读到:

  • _getcwd at MSDN
  • getcwd at Kernel.org
  • getcwd at Apple.com

应该没有内存泄漏,它也应该在Mac上正常工作?

There should be no memory leaks, and it should work on a Mac as well, correct?

更新:我恐怕在这里仍然是错误的(我试图避免创建一个确定的长度的字符数组,因为没有正确的方法来获得一个体面的长度getcwd):

UPDATE: I fear something is still wrong here (I'm trying to avoid creating a char array with a determined length, as there's no proper way to get a decent length for getcwd):

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


推荐答案

您不能调用 getcwd 使用NULL缓冲区。根据 Opengroup

You cannot call getcwd with a NULL buffer. As per the Opengroup:


如果buf是一个空指针,则getcwd()的行为是未指定的。

If buf is a null pointer, the behavior of getcwd() is unspecified.

返回NULL可以打破字符串构造函数。

Also, getcwd can return NULL which can break a string constructor.

您需要将其更改为:

char buffer[SIZE];
char *answer = getcwd(buffer, sizeof(buffer));
string s_cwd;
if (answer)
{
    s_cwd = answer;
}

这篇关于什么是跨平台的方式来获取当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆