views:

9772

answers:

7

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

I need a cross platform solution.

+1  A: 

I think THIS is what you need :)

Lukas Šalkauskas
+1  A: 

_splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w

I think this is Windows (Platform SDK) only?

Aardvark
+4  A: 

Assuming you have access to STL:

std::string filename("filename.conf");
std::string::size_type idx;

idx = filename.rfind('.');

if(idx != std::string::npos)
{
    std::string extension = filename.substr(idx+1);
}
else
{
    // No extension found
}

Edit: This is a cross platform solution since you didn't mention the platform. If you're specifically on Windows, you'll want to leverage the Windows specific functions mentioned by others in the thread.

17 of 26
+1, this is the simplest solution in case you have a **file** in a string and not a path!
Andreas Bonini
+3  A: 

The best way is to not write any code that does it but call existing methods. In windows, the PathFindExtension method is probably the simplest.

So why would you not write your own?

Well, take the strrchr example, what happens when you use that method on the following string "c:\program files\AppleGate.Net\readme"? Is ".Net\readme" the extension? It is easy to write something that works for a few example cases, but can be much harder to write something that works for all cases.

Torlack
+9  A: 

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;
  }
}
brian newman
+6  A: 

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

Your directory name is easily handled by reverse find though :).
17 of 26
+1  A: 

Using std::string's find/rfind solves THIS problem, but if you work a lot with paths then you should look at boost::filesystem::path since it will make your code much cleaner than fiddling with raw string indexes/iterators.

I suggest boost since it's a high quality, well tested, (open source and commercially) free and fully portable library.

KristianR