std::ofstream,写入前检查文件是否存在

新手上路,请多包涵

我正在使用 C++ 在 Qt 应用程序中实现文件保存功能。

我正在寻找一种方法来检查所选文件在写入之前是否已经存在,以便我可以向用户提示警告。

我正在使用 std::ofstream 我不是在寻找 Boost 解决方案。

原文由 cweston 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

这是我最喜欢的隐藏功能之一,我随时可以多次使用。

 #include <sys/stat.h>
// Function: fileExists
/**
 *  Check if a file exists
 *
 * @param[in] filename - the name of the file to check
 *
 * @return    true if the file exists, else false
*/
bool fileExists(const std::string& filename)
{
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
    {
        return true;
    }
    return false;
}

如果您没有立即将文件用于 I/O 的意图,我发现这比尝试打开文件更有品味。

原文由 Rico 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题