[Interest] Handling of ~ paths
scott at towel42.com
Thu Jun 11 20:33:51 CEST 2020
On 11/06/2020 14.03, Scott Bloom wrote:
> If you are working with a path, for use in QDir, QFileInfo, QFile etc
> etc, and the path string is using a ~, either of the form ~/foo.txt or
> ~user/foo.txt, Qt seems to be treating it as a relative path of the
> current user, and prepends “/home/scott” in my case to the path,
Uh... yeah? A path starting with "~/" or "~<user>/" has been "shorthand"
for that user's home directory ("~/" → current user) for decades. I'm not sure what you were expecting?
$ cd /
$ ls -d ~
Maybe I wasn’t clear, that is 100% exactly what I would expect.
User entry, ~/foo.txt, I would 100% expect QFileInfo( "~/foo.txt" ).absoluteFilePath() to return "/home/scott/foo.txt"
But instead what is returned is "/home/scott/~/foo.txt"
> and of course, the canonicalPath returns an empty string because that
> file path is invalid and doesn’t exist.
Why is it invalid? Did you somehow manage to have your home directory not exist?
See above, the returned path is /home/scott/~/foo.txt
> What is the Qt way to handle this? It cant be to tell your users not
> to use ~. Can it?
If your intention is to treat "~/foo" as a relative path, the first component of which is literally "~", then... yeah, don't do that; that isn't the "traditional" interpretation of such a path. If that's what you want, use "./~/foo" instead. (If you just need to suppress tilde expansion, you may be able to check for paths that start with "~" and always add "./" to the beginning of them. Beware, however, that users that expect tilde expansion to work may be confused or annoyed.)
My problem is QFileInfo, QDir and QFile do not appear to be doing the ~ expansion
More information about the Interest