我尝试了以下简短示例,以了解我正在开发的更大程序中的错误。看来QFile不支持主目录的unix(或shell的)表示法:
#include <QFile>
#include <QDebug>
int main()
{
QFile f("~/.vimrc");
if (f.open(QIODevice::ReadOnly))
{
qDebug() << f.readAll();
f.close();
}
else
{
qDebug() << f.error();
}
}
一旦我用真实的主目录路径替换了“〜”,它就会起作用。有一个简单的解决方法-启用某些设置吗?还是我必须走“丑陋”的方式,向QDir询问当前用户的主目录,然后手动将其添加到每个路径中?
附录:很明显,通常shell会执行代字号扩展,因此程序将永远不会看到它。仍然在unix shell中非常方便,我希望用于文件访问的Qt实现将包括该扩展。
最佳答案
您可以创建一个辅助函数来为您执行此操作,例如:
QString morphFile(QString s) {
if ((s == "~") || (s.startsWith("~/"))) {
s.replace (0, 1, QDir::homePath());
}
return s;
}
:
QFile vimRc(morphFile("~/.vimrc"));
QFile homeDir(morphFile("~"));
一个更完整的解决方案,也允许其他用户的主目录,可能是:QString morphFile(QString fspec) {
// Leave strings alone unless starting with tilde.
if (! fspec.startsWith("~")) return fspec;
// Special case for current user.
if ((fspec == "~") || (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, ""); // Remove leading '~'.
int len = name.indexOf('/'); // Get name (up to first '/').
len = (len == -1)
? name.length()
: len - 1;
name = name.left(idx);
// Find that user in the password file, replace with home
// directory if found, then return it. You can also add a
// Windows-specific variant if needed.
struct passwd *pwent = getpwnam(name.toAscii().constData());
if (pwent != NULL)
fspec.replace(0, len+1, pwent->pw_dir);
return fspec;
}
请记住一件事,当前解决方案不能移植到Windows(根据代码中的注释)。我怀疑这对于当前的问题是可以的,因为
.vimrc
指示不是您正在运行的平台(在Windows上是_vimrc
)。可以针对该平台量身定制解决方案,并且确实表明辅助功能解决方案非常合适,因为您只需更改一段代码即可添加。