[Interest] Handling of ~ paths

Matthew Woehlke mwoehlke.floss at gmail.com
Thu Jun 11 20:24:05 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 ~
   /home/matthew

> 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?

> 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.)

-- 
Matthew


More information about the Interest mailing list