Like to know how to get the file name extenssion

I have a utility to list the files in directory.  fileName is a string and contains the file extersion.  I like to know a easy way to parse filename and get last 3 char (extension)
pasta1Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
itsmeandnobodyelseConnect With a Mentor Commented:
>>> fileName is a string and contains the file extersion.

In C++ you can do:

    string filename = "anypath\\anydir/anyname.anyext";
    string fileext;
    int pos = (int) filename.rfind('.');
    if (pos != string::npos)
         fileext = filename.substr(pos + 1);

Regards, Alex
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi pasta1,

File Extensions are usually 3 characters, but not always.  :)

There are quite a few ways to do this.  One simple, but effective way is this:

  char *Ext;

  Ext = strrchr ((FileName.c_str ()), '.');

Ext now points to the LAST period in the String, so the extension starts at Ext + 1.


Good Luck,
Kent
0
 
IchijoCommented:
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
itsmeandnobodyelseCommented:
If it was possible that the file has no extension you should do:

    string filename = "anypath\\anydir/anyname.anyext";
    string fileext;
    int pos1 = (int) filename.rfind('.');
    int pos2 = (int) filename.find_last_of("/\\:"); // find any of /  \  or :
    if (pos1 != string::npos && (pos2 == string::npos || pos2 < pos1) )
         fileext = filename.substr(pos1 + 1);
0
 
pasta1Author Commented:
I can't seem to able to get it to work.  strchr: none of the 2 overloads could convert all the argument types
0
 
pasta1Author Commented:
I have filenames only and no paths in the file name.  The filename also have multiple periods ex test.test.test.txt  so I hoping to parse filename for the chars after the last period
0
All Courses

From novice to tech pro — start learning today.