【问题标题】:Can't write to temp folder in Windows 7 using ofstream无法使用 ofstream 写入 Windows 7 中的临时文件夹
【发布时间】:2019-03-17 19:35:31
【问题描述】:

在使用 Qt 时,我使用 Qt 方式来获取 Windows 临时文件夹。这可行,但似乎我无法写入此文件夹。

代码如下:

   const QStringList defaultFolders = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
   const QString tempFolder = defaultFolders.first();
   const QString fileName = tempFolder + "/testFile.txt";

   ofstream file(fileName.toLocal8Bit(), fstream::out);
   const bool ok = file.is_open();

   const QString msg = ok ? "Success" : "Failure";
   QMessageBox::warning(this, fileName, msg);

到目前为止我尝试了什么

  • 使用带有“\\”而不是“/”的硬编码路径
  • 使用 .toStdString().c_str() 代替 ".toLocal8bit()

备注

  • 路径中有重音字符。
  • Windows 用户是管理员
  • 我可以手动创建/删除临时文件夹中的文件,但编译的应用程序不能。
  • 我在虚拟机中运行 Windows 7
  • 如果我使用旧的 C 函数(fopen/fwrite/fclose),它可以正常工作

有人知道出了什么问题吗?

【问题讨论】:

  • 也许使用toStdWString() 而不是toLocal8Bit() 会更好? std::filesystem::path filePath(fileName.toStdWString()); std::ofstream file(filePath); 不过自己没试过。
  • 您机器上的临时路径可能包含非英文字符。 toLocal8Bit() 在这种情况下可能不起作用。如果你不熟悉字符编码,就用 QFile 和 QTextStream 代替 std 库。
  • @CongMa 你是对的,路径中有非英文字符。我已经在我的问题的注释部分指定了这一点。使用 QFile/QTextStream 可能会解决我的问题,但这不是我的问题的重点。

标签: c++ windows qt


【解决方案1】:

也许使用toStdWString() 而不是toLocal8Bit() 会更好?

std::filesystem::path filePath(fileName.toStdWString());
std::ofstream file(filePath);

【讨论】:

    猜你喜欢
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多