Get filename from QFile?

QtQt4

Qt Problem Overview


eg:

QFile f("/home/umanga/Desktop/image.jpg");

How I get only the filename - "image.jpg"?

Qt Solutions


Solution 1 - Qt

Use a QFileInfo to strip out the path (if any):

QFileInfo fileInfo(f.fileName());
QString filename(fileInfo.fileName());

Solution 2 - Qt

One approach, not necessarily the best: from a QFile, you can get the file specification with QFile::fileName():

QFile f("/home/umanga/Desktop/image.jpg");
QString str = f.fileName();

then you can just use the string features like QString::split:

QStringList parts = str.split("/");
QString lastBit = parts.at(parts.size()-1);

Solution 3 - Qt

just in addition: to seperate filename and file path having QFile f

QString path = f.fileName();
QString file = path.section("/",-1,-1);
QString dir = path.section("/",0,-2);

you don't need to create an additional fileInfo.

Solution 4 - Qt

I use this:

bool utes::pathsplit(QString source,QString *path,QString *filename)
{
QString fn;
int index;
	if (source == "") return(false);
	fn = source.section("/", -1, -1);
	if (fn == "") return(false);
	index = source.indexOf(fn);
	if (index == -1) return(false);
	*path = source.mid(0,index);
	*filename = fn;
	return(true);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshika Umanga UmagiliyaView Question on Stackoverflow
Solution 1 - QtArnold SpenceView Answer on Stackoverflow
Solution 2 - QtpaxdiabloView Answer on Stackoverflow
Solution 3 - QtrefuzeeView Answer on Stackoverflow
Solution 4 - QtfyngyrzView Answer on Stackoverflow