Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 232
  • Last Modified:

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)
0
pasta1
Asked:
pasta1
1 Solution
 
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
 
itsmeandnobodyelseCommented:
>>> 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
 
IchijoCommented:
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now