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.
QString path = f. fileName(); QString file = path. section("/",-1,-1); QString dir = path. section("/",0,-2);
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);
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.
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.
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With