QDir mkpath 返回 true,但未创建目录

QDir mkpath returns true, but directory not created

本文关键字:创建目录 true mkpath 返回 QDir      更新时间:2023-10-16

我在Linux上使用Qt创建路径时遇到了一个奇怪的问题。我编写了一个独立的测试程序,为它们的存在创建路径和测试。这将按预期工作并创建目录。

/* make path */
QString p("/usr2/archive/S1234ABC/5/6");
QDir d;
if (d.mkpath(p)) qDebug() << "mkpath() returned true";
else qDebug() << "mkpath() returned false";
QDir d2;
if (d2.exists(p)) qDebug() << "exists() returned true";
else qDebug() << "exists() returned false";

我在另一个项目中将该测试示例制作成更健壮的功能。但它不起作用...mkpath(( 和 exists(( 返回 true,但硬盘上不存在路径。

bool nidb::MakePath(QString p, QString &msg) {
    if ((p == "") || (p == ".") || (p == "..") || (p == "/") || (p.contains("//")) || (p == "/root") || (p == "/home")) {
        msg = "Path is not valid [" + p + "]";
        return false;
    }
    WriteLog("MakePath() called with path ["+p+"]");
    QDir path;
    if (path.mkpath(p)) {
        WriteLog("MakePath() mkpath returned true [" + p + "]");
        if (path.exists()) {
            WriteLog("MakePath() Path exists [" + p + "]");
            msg = QString("Destination path [" + p + "] created");
        }
        else {
            WriteLog("MakePath() Path does not exist [" + p + "]");
            msg = QString("Unable to create destination path [" + p + "]");
            return false;
        }
    }
    else {
        msg = QString("MakePath() mkpath returned false [" + p + "]");
        return false;
    }
    return true;
}

我的程序的输出:

[2019/06/04 13:19:37][26034] MakePath() called with path [/usr2/archive/S0836VYL/6/5/dicom]
[2019/06/04 13:19:37][26034] MakePath() mkpath returned true [/usr2/archive/S0836VYL/6/5/dicom]
[2019/06/04 13:19:37][26034] MakePath() Path exists [/usr2/archive/S0836VYL/6/5/dicom]

以及命令行的输出...

[onrc@ado2dev /]$ cd /usr2/archive/S0836VYL/6/5/dicom
-bash: cd: /usr2/archive/S0836VYL/6/5/dicom: No such file or directory
[onrc@ado2dev /]$ 

我错过了什么??

尝试使用这个:

QString p("/usr2/archive/S1234ABC/5/6");
QDir d(p);
if(!d.exists() && !d.mkpath(p)) qDebug() << "Error: can't create folder '"<< p <<"'.";
else qDebug() << "Folder '"<< p <<"' exists or created successfully".

希望对您有所帮助。

好吧,这是记录簿的一个...

问题是在插入数据库之前将空终止符附加到S1234ABC字符串的末尾。该字符串后来用于创建上述路径。该S1234ABC字符串是使用以下代码创建的:

QString prefix = "S";
QChar C1, C2, C3, etc... (randomly generated characters)
QString newID = prefix + C1 + C2 + etc...

这将创建一个末尾带有 \0 的 QString。Qt将此值存储在MySQL数据库中,然后我将其拉回Qt并尝试使用它创建路径。由于它是一个以空结尾的字符串,因此在phpMyAdmin,xterm和日志文件中看起来很正常。除了。。。在Windows的puTTY中,我看到了它试图创建的奇怪路径:

/usr2/archive/S0836VYLu0000/10/3/dicom

值得庆幸的是,puTTY显示了实际的Unicode值,而不是忽略它。谢谢腻子!我从来没有,永远不会想通这一点...

使用QStrings而不是QChar重新创建S1234ABC字符串解决了该问题。现在我在数据库中有常规的旧字符串和正常的路径。