我正在使用 C++ 在 Qt 应用程序中实现文件保存功能。
我正在寻找一种方法来检查所选文件在写入之前是否已经存在,以便我可以向用户提示警告。
我正在使用 std::ofstream
我不是在寻找 Boost 解决方案。
原文由 cweston 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 C++17 的 std::filesystem::exists
:
#include <filesystem> // C++17
#include <iostream>
namespace fs = std::filesystem;
int main()
{
fs::path filePath("path/to/my/file.ext");
std::error_code ec; // For using the noexcept overload.
if (!fs::exists(filePath, ec) && !ec)
{
// Save to file, e.g. with std::ofstream file(filePath);
}
else
{
if (ec)
{
std::cerr << ec.message(); // Replace with your error handling.
}
else
{
std::cout << "File " << filePath << " does already exist.";
// Handle overwrite case.
}
}
}
另见 std::error_code
。
如果要检查要写入的路径是否实际上是常规文件,请使用 std::filesystem::is_regular_file
。
原文由 Roi Danton 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
这是我最喜欢的隐藏功能之一,我随时可以多次使用。
如果您没有立即将文件用于 I/O 的意图,我发现这比尝试打开文件更有品味。