Directories in C++ - 10.13 Extracting a File Extension from a String (Page 4 of 4 )
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.
Extracting a File Extension from a String
Example 10-20. Getting a file extension from a filename
#include <iostream> #include <string>
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) << ""\n"; }
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 <string> 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
Recipes 4.9 and 10.12
Please check back next week for the conclusion to this article.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.