Home > Backend Development > C++ > How to get file extension using C++?

How to get file extension using C++?

王林
Release: 2024-06-05 12:23:56
Original
1145 people have browsed it

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 using C++?

How to get file extension in C++

Getting file extension in C++ can help you:

  • Identify and process different file types
  • Verify that the input file name has a valid extension
  • Implement file archiving and management

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template