Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to remove extension from a filename?

Tags:

c++

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".

like image 807
Flarmar Brunjd Avatar asked Jun 20 '11 21:06

Flarmar Brunjd


People also ask

How do I disassociate a file extension?

bat Now right click any file you want to disassociate and choose 'Open with' - 'Choose another app' -' More Apps' Check the box marked 'Always use this app' Scroll to the bottom and click 'Look for another app on this PC' Navigate to the XXX. bat on your Desktop and select that Finally delete XXX.

How do I remove a double filename extension?

Open File Explorer and click View tab, Options. In Folder Options dialog, move to View tab, untick Hide extensions for known file types option, OK. Then you will se file's extension after its name, remove it.

How do I separate filenames and extensions?

The function splitext() in os. path allows you to separate the root and extension of a specified file path. A tuple made up of the root string and the extension string is the function's output.


2 Answers

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

like image 78
Adithya Surampudi Avatar answered Sep 19 '22 17:09

Adithya Surampudi


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);  } 
like image 23
orlp Avatar answered Sep 19 '22 17:09

orlp