Using C strings I would write the following code to get the file name from a file path:
#include <string.h>
const char* filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
const char* fileName = strrchr(progPath, '\\');
if (fileName)
++fileName;
else
fileName = filePath;
How to do the same with C++ strings? (i.e. using std::string
from #include <string>
)
The closest equivalent is rfind
:
#include <string>
std::string filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
std::string::size_type filePos = filePath.rfind('\\');
if (filePos != std::string::npos)
++filePos;
else
filePos = 0;
std::string fileName = filePath.substr(filePos);
Note that rfind
returns an index into the string (or npos
), not a pointer.
To find the last occurence of a symbol in a string use std::string::rfind
std::string filename = "dir1\\dir2\\filename";
std::size_t pos = filename.rfind( "\\" );
However, if you're handling filenames and pathes more often, have a look at boost::filesystem
boost::filesystem::path p("dir1\\dir2\\filename");
std::string filename = p.filename().generic_string(); //or maybe p.filename().native();
Either call string::rfind()
, or call std::find
using reverse iterators (which are returned from string::rbegin()
and string::rend()
).
find
might be a little bit more efficient since it explicitly says that you're looking for a matching character. rfind()
looks for a substring and you'd give it a length 1 string, so it finds the same thing.
Apart from rfind()
, you can also use find_last_of()
You have an example too written in cplusplus.com which is same as your requirement.