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
Removing extension of a file name in 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();
f
is like "filename.tif", but I want it to be "filename".
f
就像 "filename.tif",但我希望它是"filename"。
采纳答案by Shf
You can split
fileName
with "." as separator like this:
你可以split
fileName
用“.” 作为这样的分隔符:
QString croped_fileName=fileName.split(".",QString::SkipEmptyParts).at(0);
or use section
function of QString to take the first part before "." like this:
或使用section
QString 的函数取“.”之前的第一部分。像这样:
QString croped_fileName=fileName.section(".",0,0);
回答by Angew is no longer proud of SO
QFileInfo
has 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::split
and use the .
as the place where to split it.
您可以使用QString::split
和使用.
作为拆分它的地方。
QStringList list1 = str.split(".");
QStringList list1 = str.split(".");
That will return a QStringList
with {"filename", "extenstion"}
. Now you can get your filename without the extension.
那将返回一个QStringList
with {"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"