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?
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.
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());
}
来源:https://stackoverflow.com/questions/4807629/how-do-i-find-the-current-directory