How can I extract the file name and extension from a path in C++

Octavian picture Octavian · Dec 13, 2010 · Viewed 92.4k times · Source

I have a list of files stored in a .log in this syntax:

c:\foto\foto2003\shadow.gif
D:\etc\mom.jpg

I want to extract the name and the extension from this files. Can you give a example of a simple way to do this?

Answer

Nickolay Merkin picture Nickolay Merkin · Feb 17, 2014

To extract a filename without extension, use boost::filesystem::path::stem instead of ugly std::string::find_last_of(".")

boost::filesystem::path p("c:/dir/dir/file.ext");
std::cout << "filename and extension : " << p.filename() << std::endl; // file.ext
std::cout << "filename only          : " << p.stem() << std::endl;     // file