qtqurl

Make the difference between a file path and a url in Qt


If I have a string which could be either a file or a URL, is there any existing clever method I could use to differentiate them?

For instance:

This is to load a designer UI file, so I need to make a local temporary copy of the remote file. So the bottom line is to know when I need to download the file.


Solution

  • Well, you might want to construct a QUrl object out of these strings and verify whether these URLs refer to local files. I.e.:

    static bool isLocalFile(const QString &str)
    {
        return QUrl::fromUserInput(str).isLocalFile();
    }
    

    With your strings

    QString s1("/Users/user/Documents/mydoc.txt");
    QString s2("c:\\Program Files\\myapp\\mydoc.doc");
    QString s3("https://mywebsite.com/mydoc.txt");
    QString s4("ftp://myserver.com/myfile.txt");
    
    bool b = isLocalFile(s1); // a path
    b = isLocalFile(s2); // a path
    b = isLocalFile(s3); // not a path
    b = isLocalFile(s4); // not a path