路径错了,怎么办

Path is wrong, what to do?

本文关键字:怎么办 错了 路径      更新时间:2023-10-16

我想写点东西到我的道路上。

我的代码如下

QString Log::logPacketsPath = QDir::currentPath() + "/logs/Packets/";
int userID = 1;
QString text = "test 1 2 3";

QFile logPacketFile(logPacketsPath + "UserID: " + userID + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");
if (logPacketFile.open(QFile::WriteOnly | QFile::Text | QFile::Append))
{
    QTextStream out(&logPacketFile);
    out << "[" << QDateTime::currentDateTime().toString("dd.MM.yy, hh:mm:ss") << "]: " << text << "n";
    logPacketFile.close();
}

但它只创建名为"UserID"的文件,其中没有任何内容。

你知道错误在哪里吗?

我不确定您使用的是哪个操作系统,但是 Windows文件名中的":"无效。

接下来,您应该在关闭文件之前刷新QTextStream

out.flush();
logPacketFile.close();

或创建其他范围:

{
    QTextStream out(&logPacketFile);
    out << "[" << QDateTime::currentDateTime().toString("dd.MM.yy, hh:mm:ss") << "]: " << text << "n";
}
logPacketFile.close();

此外,正如 Chemobyl 指出的那样,通过将int userID连接到文件路径可能会遇到麻烦。我建议使用字符串格式来创建文件名:

QString logPacketFile("%1UserID%2 - %3.log")
         .arg(logPacketsPath)
         .arg(userID)
         .arg(QDateTime::currentDateTime().toString("dd.MM.yy"));

int转换为QString

使用QString::number().

使用当前代码输出:

"C:/.../logs/Packets/UserID [bad symbols here] - 17.11.14.log" 

输出方式

QFile logPacketFile(logPacketsPath + "UserID " + QString::number(userID) + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");//removed colon

是:

"C:/.../logs/Packets/UserID 1 - 17.11.14.log" 

这是大麻烦的根源。请参阅下一篇:

int userID = 70;
QString text = "test 1 2 3";
QFile logPacketFile(logPacketsPath + "UserID " + userID + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");

输出:

.../UserID F - 17.11.14.log" 

注意 F ,不是70,因为 operator+ 认为您使用简单的字符并且 char 中的70F

http://www.asciitable.com/

所以我强烈建议你使用QString::number来防止错误。