Easy way to remove extension from a filename?
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".
Solution 1:
size_t lastindex = fullname.find_last_of(".");
string rawname = fullname.substr(0, lastindex);
Beware of the case when there is no "." and it returns npos
Solution 2:
This works:
std::string remove_extension(const std::string& filename) {
size_t lastdot = filename.find_last_of(".");
if (lastdot == std::string::npos) return filename;
return filename.substr(0, lastdot);
}