次のようなヘルパー関数を作成して、これを行うことができます。
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
これは、実行しているプラットフォームではないことを示しているため ( _vimrc
Windows 上にあります) 、当面の質問には問題ないと思います。
そのプラットフォームに合わせてソリューションを調整することは可能であり、実際にヘルパー関数ソリューションが適切であることを示しています。それを追加するにはコードを1 つ変更するだけでよいからです。