Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting filename from path using QString basic functions

Tags:

path

qt

qstring

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.

like image 965
Tomáš Zato - Reinstate Monica Avatar asked Mar 14 '16 11:03

Tomáš Zato - Reinstate Monica


People also ask

How to get file name from path in Qt?

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

How it is possible to get path and fileName of the given file?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

How do you use relative path in Qt?

This is a relative path: QDir dir("../MyProjects/ProjectB"); If the current working directory is not a sub directory of "C:\MyDevelopment\", the path will be probably invalid (not existing). This will return the path to the passed name relative to the above directory.

What is QFileInfo?

QFileInfo provides information about a file's name and position (path) in the file system, its access rights and whether it is a directory or symbolic link, etc. The file's size and last modified/read times are also available. QFileInfo can also be used to obtain information about a Qt resource.


2 Answers

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.

like image 93
Ilya Avatar answered Sep 27 '22 20:09

Ilya


From QString::right():

"Returns a substring that contains the n rightmost characters of the string."

You're using the index as a count. You'd have to use .size() - .indexOf().

like image 21
weeska Avatar answered Sep 27 '22 19:09

weeska