Getting filename from path using QString basic functions

Tomáš Zato - Reinstate Monica picture Tomáš Zato - Reinstate Monica · Mar 14, 2016 · Viewed 10.4k times · Source

There's some path as QString:

QString path = "C:/bla/blah/x/y/file.xls";

I thought that maybe getting last offset of / would be a good start. I could then use right method (no pun intended) to get everything after that character:

path = path.right(path.lastIndexOf("/"));

or in a more compatible way:

path = path.right(std::max(path.lastIndexOf("\\"), path.lastIndexOf("/")));

Those both have the same bad result:

ah/x/y/file.xls

What's wrong here? Obviously the path is getting cut too soon, but it's even weirder it's not cut at any of / at all.

Answer

Ilya picture Ilya · Mar 14, 2016

The QString method you want is mid, not right (right counts from the end of the string):

path = path.mid(path.lastIndexOf("/"));

mid has a second parameter, but when it's omitted you get the rightmost part of the string.

And for a cleaner / more universal code:

QFileInfo fi("C:/bla/blah/x/y/file.xls");
QString fileName = fi.fileName(); 

NB QFileInfo doesn't query the file system when it doesn't have to, and here it doesn't have to because all the infos are in the string.