Given a string "filename.conf", how to I verify the extension part?
I need a cross platform solution.
Given a string "filename.conf", how to I verify the extension part?
I need a cross platform solution.
_splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w
I think this is Windows (Platform SDK) only?
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.
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.
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;
}
}
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
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.