Get filename from QFile?

eg:

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

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


Solution 1:

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

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

Solution 2:

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:

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:

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);
}