59

eg:

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

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

Ashika Umanga Umagiliya
  • 8,988
  • 28
  • 102
  • 185

4 Answers4

113

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

QFileInfo fileInfo(f.fileName());
QString filename(fileInfo.fileName());
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
Arnold Spence
  • 21,942
  • 7
  • 74
  • 67
16

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);
Lion King
  • 32,851
  • 25
  • 81
  • 143
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
11

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.

refuzee
  • 408
  • 4
  • 15
1

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);
}
fyngyrz
  • 2,458
  • 2
  • 36
  • 43
  • Smart, but for me it seems like a long U turn. +1 Because i had to search for the meaning of **QString::section()** and **QString::mid()**, i didn't knew about them – Eyad Mohammed Osama Apr 08 '20 at 01:45