What is the simplest way to get the file name that from a path?
string filename = \"C:\\\\MyDirectory\\\\MyFile.bat\"
In this example, I s
_splitpath should do what you need. You could of course do it manually but _splitpath
handles all special cases as well.
EDIT:
As BillHoag mentioned it is recommended to use the more safe version of _splitpath
called _splitpath_s when available.
Or if you want something portable you could just do something like this
std::vector splitpath(
const std::string& str
, const std::set delimiters)
{
std::vector result;
char const* pch = str.c_str();
char const* start = pch;
for(; *pch; ++pch)
{
if (delimiters.find(*pch) != delimiters.end())
{
if (start != pch)
{
std::string str(start, pch);
result.push_back(str);
}
else
{
result.push_back("");
}
start = pch + 1;
}
}
result.push_back(start);
return result;
}
...
std::set delims{'\\'};
std::vector path = splitpath("C:\\MyDirectory\\MyFile.bat", delims);
cout << path.back() << endl;