How to get file extension from string in C++


Question

Given a string "filename.conf", how to I verify the extension part?

I need a cross platform solution.

1
73
7/11/2019 1:36:43 PM

Accepted Answer

You have to make sure you take care of file names with more then one dot. example: c:\.directoryname\file.name.with.too.many.dots.ext would not be handled correctly by strchr or find.

My favorite would be the boost filesystem library that have an extension(path) function

34
1/20/2010 8:53:52 PM

Is this too simple of a solution?

#include <iostream>
#include <string>

int main()
{
  std::string fn = "filename.conf";
  if(fn.substr(fn.find_last_of(".") + 1) == "conf") {
    std::cout << "Yes..." << std::endl;
  } else {
    std::cout << "No..." << std::endl;
  }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon