What is the simplest way to get the directory that a file is in? I\'m using this to find the working directory.
string filename = \"C:\\MyDirectory\\MyFile.b
The quick and dirty:
Note that you must also look for /
because it is allowed alternative path separator on Windows
#include
#include
std::string dirnameOf(const std::string& fname)
{
size_t pos = fname.find_last_of("\\/");
return (std::string::npos == pos)
? ""
: fname.substr(0, pos);
}
int main(int argc, const char *argv[])
{
const std::string fname = "C:\\MyDirectory\\MyFile.bat";
std::cout << dirnameOf(fname) << std::endl;
}