How do I find the current directory?

浪子不回头ぞ 提交于 2019-11-27 09:04:23

Since you added the visual-c++ tag I'm going to suggest the standard windows function to do it. GetCurrentDirectory

Usage:

TCHAR pwd[MAX_PATH];
GetCurrentDirectory(MAX_PATH,pwd);
MessageBox(NULL,pwd,pwd,0);

Boost filesystem library provides a clean solution

current_path()

Use _getcwd to get the current working directory.

rubenvb

Here's the most platform-agnostic answer I got a while ago:

How return a std::string from C's "getcwd" function

It's pretty long-winded, but does exactly what it's supposed to do, with a nice C++ interface (ie it returns a string, not a how-long-are-you-exactly?-(const) char*).

To shut up MSVC warnings about deprecation of getcwd, you can do a

#if _WIN32
    #define getcwd _getcwd
#endif // _WIN32

This code works for Linux and Windows:

#include <stdio.h>  // defines FILENAME_MAX
#include <unistd.h> // for getcwd()
#include <iostream>

std::string GetCurrentWorkingDir();

int main()
{
   std::string str = GetCurrentWorkingDir();
   std::cout << str;
   return 0;
}
std::string GetCurrentWorkingDir()
{
    std::string cwd("\0",FILENAME_MAX+1);
    return getcwd(&cwd[0],cwd.capacity());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!