Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 770
Octavian Avatar asked Dec 13 '10 16:12

Octavian


People also ask

How do I get the filename from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

How do I extract file extensions?

You can extract the file extension of a filename string using the os. path. splitext method. It splits the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period.

Does path contain file name?

Paths include the root, the filename, or both. That is, paths can be formed by adding either the root, filename, or both, to a directory.


1 Answers

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 
like image 51
Nickolay Merkin Avatar answered Sep 27 '22 22:09

Nickolay Merkin