Why can't QFile read from the ~ directory?

I tried the following short example to find out about a bug in a larger program I'm working on. It seems that QFile does not support nonix (or shell) for the home directory:

#include <QFile>
#include <QDebug>

int main()
{
        QFile f("~/.vimrc");
        if (f.open(QIODevice::ReadOnly))
        {
                qDebug() << f.readAll();
                f.close();
        }
        else
        {
                qDebug() << f.error();
        }
}

As soon as I replace "~" with my real path to the home directory, it works. Is there an easy workaround - some settings allow? Or do I need to go the "ugly" way and ask QDir for the current user's home directory and add it manually to each path?

Feature: . It is clear that usually the shell performs tilde expansion, so programs have never seen this. However, it is so convenient in unix shells that I was hoping that the Qt implementation for file access would include this extension.

+5
4

, - (untested):

QString morphFile (QString s) {
    if (s.startsWith ("~/"))
        s.replace (0, 1, QDir::homePath());
    return s;
}
:
QFile f(morphFile ("~/.vimrc"));

( , Qt , ):

QString morphFile (QString fspec) {
    // Leave strings not starting with tilde.

    if (!fspec.startsWith ("~"))
        return fspec;

    // Special case for current user.

    if (fspec.startsWith ("~/")) {
        fspec.replace (0, 1, QDir::homePath());
        return fspec;
    }

    // General case for any user. Get user name and length of it.

    QString name (fspec);
    name.replace (0, 1, "");
    int len = name.indexOf ('/');
    if (len == -1)
        len = name.length()
    else
        len--;
    name = name.left (idx);

    // Find that user in the passwd file, replace with home directory
    //   if found, then return it.

    struct passwd *pwent = getpwnam (name.toAscii().constData());
    if (pwent != NULL)
        fspec.replace (0, len+1, pwent->pw_dir);

    return fspec;
}
+8

UNIX; - , , , .

+3
+2
source

Take a look at the C library function glob, which will do tilde extensions (and possibly wildcard expansion and various other functions).

0
source

All Articles