There are two ways to get the file extension in C++: Use the string manipulation function std::find to find the extension delimiter. Use the extension function from the boost::filesystem::path class in the Boost library.
How to get file extension in C++
Getting file extension in C++ can help you:
Method 1: Use string operations
You can use the standard library function std::find
to find the last dot (i.e. extension separator) in the file path.
#include <iostream> #include <string> std::string get_file_extension(const std::string& filename) { auto last_dot = filename.find_last_of('.'); if (last_dot == std::string::npos) { return ""; // 没有扩展名 } return filename.substr(last_dot + 1); } int main() { std::string filename = "example.txt"; std::cout << "File extension: " << get_file_extension(filename) << std::endl; return 0; }
Method 2: Use boost::filesystem
If you are using the Boost library, you can use boost::filesystem
extension function in ::path
class.
#include <boost/filesystem.hpp> std::string get_file_extension(const std::string& filename) { boost::filesystem::path path(filename); return path.extension().string(); } int main() { std::string filename = "example.txt"; std::cout << "File extension: " << get_file_extension(filename) << std::endl; return 0; }
The above is the detailed content of How to get file extension using C++?. For more information, please follow other related articles on the PHP Chinese website!