16

I am trying to read a file which I read previously successfully. I am reading it through a library, and I am sending it as-is to the library (i.e. "myfile.txt"). I know that the file is read from the working/current directory.

I suspect that the current/working directory has changed somehow. How do i check what is the current/working directory?

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
lital maatuk
  • 5,921
  • 20
  • 57
  • 79

5 Answers5

25

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);
monoceres
  • 4,722
  • 4
  • 38
  • 63
  • Interesting. Are you sure it doesn't just write the part that fits in the buffer? – monoceres May 31 '13 at 13:02
  • Really sorry... My program was incorrect.. I just deleted my comments so they wouldn't mislead others. I tested it again: If the buffer size specified is not large enough, the buffer will be kept unmodified and the desired size will be returned. – yaobin Jun 13 '13 at 00:55
  • Remember to add `#include ` to code file before this call. – heLomaN Mar 04 '21 at 02:51
8

Boost filesystem library provides a clean solution

current_path()
Dr G
  • 3,987
  • 2
  • 19
  • 25
6

Use _getcwd to get the current working directory.

Hasturkun
  • 35,395
  • 6
  • 71
  • 104
4

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
Community
  • 1
  • 1
rubenvb
  • 74,642
  • 33
  • 187
  • 332
4

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());
}
IluxaKuk
  • 389
  • 3
  • 7
  • It doesn't work for me. Error: E1696 cannot open source file "unistd.h". The unistd.h file is not part of C or C++ (http://www.cplusplus.com/forum/beginner/59238/) – NN2 Jan 30 '21 at 21:34
  • 1
    Only works if you are using gcc. Does not work if you are using visual studio – cup Mar 07 '22 at 14:48