What is a cross-platform way to get the current directory?

杀马特。学长 韩版系。学妹 提交于 2019-11-27 22:06:12

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

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

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

You'll need to change that to something like:

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

If it is no problem for you to include, use boost filesystem for convenient cross-platform filesystem operations.

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

Here is an example.

EDIT: as pointed out by Roi Danton in the comments, filesystem became part of the ISO C++ in C++17, so boost is not needed anymore:

std::filesystem::current_path();
Matthew Flaschen

Calling getcwd with a NULL pointer is implementation defined. It often does the allocation for you with malloc (in which case your code does have a memory leak). However, it isn't guaranteed to work at all. So you should allocate your own buffer.

char *cwd_buffer = malloc(sizeof(char) * max_path_len);
char *cwd_result = getcwd(cwd_buffer, max_path_len);

The Open Group has an example showing how to get the max path length from _PC_PATH_MAX. You could consider using MAX_PATH on Windows. See this question for caveats to this number on both platforms.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!