Extracting a File Extension from a String

Problem

Given a filename or a complete path, you need to retrieve the file extension, which is the part of a filename that follows the last period. For example, in the filenames src.cpp, Window.class, and Resume.doc, the file extensions are .cpp, .class, and .doc.

Solution

Convert the file and/or pathname to a string, use the rfind member function to locate the last period, and return everything after that. Example 10-20 shows how to do this.

Example 10-20. Getting a file extension from a filename

#include 
#include 

using std::string;

string getFileExt(const string& s) {

 size_t i = s.rfind('.', s.length( ));
 if (i != string::npos) {
 return(s.substr(i+1, s.length( ) - i));
 }

 return("");
}

int main(int argc, char** argv) {

 string path = argv[1];

 std::cout << "The extension is "" << getFileExt(path) << ""
";
}

 

Discussion

To get an extension from a filename, you just need to find out where the last dot "." is and take everything to the right of that. The standard string class, defined in contains functions for doing both of these things: rfind and substr.

rfind will search backward for whatever you sent it (a char in this case) as the first argument, starting at the index specified by the second argument, and return the index where it was found. If the pattern wasn't found, rfind will return string::npos. substr also takes two arguments. The first is the index of the first element to copy, and the second is the number of characters to copy.

The standard string class contains a number of member functions for finding things. See Recipe 4.9 for a longer discussion of string searching.

See Also

Recipe 4.9 and Recipe 10.12

Building C++ Applications

Code Organization

Numbers

Strings and Text

Dates and Times

Managing Data with Containers

Algorithms

Classes

Exceptions and Safety

Streams and Files

Science and Mathematics

Multithreading

Internationalization

XML

Miscellaneous

Index



C++ Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2006
Pages: 241

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net