Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

10.16. Replacing a File Extension

Problem

Given a filename, or a path and filename, you want to replace the file’s extension. For example, if you are given thesis.tex, you want to convert it to thesis.txt.

Solution

Use string’s rfind and replace member functions to find the extension and replace it. Example 10-25 shows you how to do this.

Example 10-25. Replacing a file extension

#include <iostream>
#include <string>

using std::string;

void replaceExt(string& s, const string& newExt) {

   string::size_type i = s.rfind('.', s.length());

   if (i != string::npos) {
      s.replace(i+1, newExt.length(), newExt);
   }
}

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

   string path = argv[1];

   replaceExt(path, "foobar");
   std::cout << "The new name is \"" << path << "\"\n";
}

Discussion

This solution is similar to the ones in the preceding recipes, but in this case I used replace to replace a portion of the string with a new string. replace has three parameters. The first parameter is the index where the replace should begin, and the second is the number of characters to delete from the destination string. The third parameter is the value that will be used to replace the deleted portion of the string.

See Also

Recipe 4.9

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page