C++ 在 Qt 中删除文件名的扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15244911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:12:36  来源:igfitidea点击:

Removing extension of a file name in Qt

c++qt

提问by Engine

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

我正在使用 Qt 从用户那里获取文件名:

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 :

它有效,但我需要没有扩展名的文件名,在 Qt 中可以吗??当我尝试:

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

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

f就像 "filename.tif",但我希望它是"filename"

采纳答案by Shf

You can splitfileNamewith "." as separator like this:

你可以splitfileName用“.” 作为这样的分隔符:

QString croped_fileName=fileName.split(".",QString::SkipEmptyParts).at(0);

or use sectionfunction of QString to take the first part before "." like this:

或使用sectionQString 的函数取“.”之前的第一部分。像这样:

QString croped_fileName=fileName.section(".",0,0);

回答by Angew is no longer proud of SO

QFileInfohas two functions for this:

QFileInfo为此有两个功能:

QString QFileInfo::completeBaseName () const

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

返回删除了最短扩展名的文件名 ( file.tar.gz-> file.tar)

QString QFileInfo::baseName () const

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

返回删除最长扩展名的文件名 ( file.tar.gz-> file)

回答by leemes

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("."));
}

回答by Tony The Lion

You can use QString::splitand use the .as the place where to split it.

您可以使用QString::split和使用.作为拆分它的地方。

QStringList list1 = str.split(".");

QStringList list1 = str.split(".");

That will return a QStringListwith {"filename", "extenstion"}. Now you can get your filename without the extension.

那将返回一个QStringListwith {"filename", "extenstion"}。现在您可以获得没有扩展名的文件名。

回答by jarzec

To get absolute path without extension for QFileInfo fileInfo("/a/path/to/foo.tar.gz")you can use:

要获得没有扩展名的绝对路径,QFileInfo fileInfo("/a/path/to/foo.tar.gz")您可以使用:

QDir(file_info.absolutePath()).filePath(file_info.baseName());

to get "/a/path/to/foo"or

得到"/a/path/to/foo"

QDir(file_info.absolutePath()).filePath(file_info.completeBaseName());

to get "/a/path/to/foo.tar"

要得到 "/a/path/to/foo.tar"