路径错了,怎么办
Path is wrong, what to do?
我想写点东西到我的道路上。
我的代码如下
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 中的70
是F
:
http://www.asciitable.com/
所以我强烈建议你使用QString::number
来防止错误。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- 首要问题的答案让值班员搞错了
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 我的C++线程做错了什么?
- 如何正确使用 >=?(a+f()+c)>=0 错了吗?
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- 没有输出的合并排序我做错了什么?
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 在C++中使用 AKS 素数测试计算双胞胎素数 我做错了什么?
- 指针相关的UE4崩溃.我的指针哪里错了?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我正在尝试学习如何在 c++ 中传递指针,但出现错误:没有用于调用"test"的匹配函数。我做错了什么?
- FFMPEG,C++,内存泄漏,我做错了什么?
- 我做错了什么?反向字符串 C++
- 我在这个课上做错了什么?
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 在不使用内置库函数的情况下添加字符串,我做错了什么?
- 路径错了,怎么办