Easy way to remove extension from a filename?

Viewed 85964

I am trying to grab the raw filename without the extension from the filename passed in arguments:

int main ( int argc, char *argv[] )
{
    // Check to make sure there is a single argument
    if ( argc != 2 )
    {
        cout<<"usage: "<< argv[0] <<" <filename>\n";
        return 1;
    }

    // Remove the extension if it was supplied from argv[1] -- pseudocode
    char* filename = removeExtension(argv[1]);

    cout << filename;

}

The filename should for example be "test" when I passed in "test.dat".

11 Answers

Since C++17 you can use std::filesystem::path::replace_extension with a parameter to replace the extension or without to remove it:

#include <iostream>
#include <filesystem>
 
int main()
{
    std::filesystem::path p = "/foo/bar.txt";
    std::cout << "Was: " << p << std::endl;
    std::cout << "Now: " << p.replace_extension() << std::endl;
}

Compile it with:

g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

Running the resulting binary leaves you with:

Was: "/foo/bar.txt"
Now: "/foo/bar"

However this does only remove the last file extension:

Was: "/foo/bar.tar.gz"
Now: "/foo/bar.tar"

More complex, but with respect to special cases (for example: "foo.bar/baz", "c:foo.bar", works for Windows too)

std::string remove_extension(const std::string& path) {
    if (path == "." || path == "..")
        return path;

    size_t pos = path.find_last_of("\\/.");
    if (pos != std::string::npos && path[pos] == '.')
        return path.substr(0, pos);

    return path;
}

Try the following trick to extract the file name from path with no extension in c++ with no external libraries in c++ :

#include <iostream>
#include <string>

using std::string;

string getFileName(const string& s) {
char sep = '/';
#ifdef _WIN32
sep = '\\';
#endif
size_t i = s.rfind(sep, s.length());
if (i != string::npos) 
{
  string filename = s.substr(i+1, s.length() - i);
  size_t lastindex = filename.find_last_of("."); 
  string rawname = filename.substr(0, lastindex); 
  return(rawname);
}

return("");
}

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

string path = "/home/aymen/hello_world.cpp";
string ss = getFileName(path);
std::cout << "The file name is \"" << ss << "\"\n";
}
Related