Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing extension of a file name in Qt

Tags:

I'm using Qt to get a file name from the user:

QString fileName = QFileDialog::getOpenFileName(this,tr("Select an image file"),"d:\\",tr("Image files(*.tiff *.tif )")); 

It works, but I need the file name without its extension, is it possible in Qt?? whenn I try :

QString f = QFileInfo(fileName).fileName(); 

f is like "filename.tif", but I want it to be "filename".

like image 262
Engine Avatar asked Mar 06 '13 10:03

Engine


People also ask

How do I remove the file extension from a file path?

Using Path. To get the full path without the extension, consider using Path. ChangeExtension() method. It takes two parameters – the path to modify and the new extension. The idea is to pass null to the ChangeExtension() method parameter to remove the existing extension.

What is QFileInfo?

QFileInfo provides information about a file's name and position (path) in the file system, its access rights and whether it is a directory or symbolic link, etc. The file's size and last modified/read times are also available. QFileInfo can also be used to obtain information about a Qt resource.


2 Answers

QFileInfo has two functions for this:

QString QFileInfo::completeBaseName () const 

Returns file name with shortest extension removed (file.tar.gz -> file.tar)

QString QFileInfo::baseName () const 

Returns file name with longest extension removed (file.tar.gz -> file)

like image 74
Angew is no longer proud of SO Avatar answered Sep 19 '22 09:09

Angew is no longer proud of SO


To cope with filenames containing multiple dots, look for the last one and take the substring until that one.

int lastPoint = fileName.lastIndexOf("."); QString fileNameNoExt = fileName.left(lastPoint); 

Of course this can (and should) be written as a helper function for reuse:

inline QString withoutExtension(const QString & fileName) {     return fileName.left(fileName.lastIndexOf(".")); } 
like image 24
leemes Avatar answered Sep 21 '22 09:09

leemes