How to check file extension using C++

Hello
I am trying to make a program that check any file and get the extension like :
*If i have image.png the program well return a that this file has a png extension etc...
So any one who help me with a source code.
Thank you C++ers
Last edited on
You don't really even need that. Just check to see if the last four characters in the filename == ".png".
The extension doesn't have to be 3 characters long. The OP wants to check any file type.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

string getExtension( const string &str )
{
   size_t p = str.rfind( '.' );
   if ( p == string::npos || p == str.size() - 1 ) return "";
   return str.substr( p + 1 );
}

int main()
{
   string tests[] = { "one.doc", "two.xls", "help", "spam.txt.exe" };
   for ( string s : tests )
   {
      string ext = getExtension( s );
      cout << s << " : " << ( ext.empty() ? "No extension" : "extension " + ext ) << '\n';
   }
}


one.doc : extension doc
two.xls : extension xls
help : No extension
spam.txt.exe : extension exe

"hello.world/filename"

http://www.cplusplus.com/forum/general/34348/#msg185786


[edit]
These days, though, you can just use filesystem::path, as AbstractionAnon suggested. He even linked to some good examples. :O)
Last edited on
Topic archived. No new replies allowed.