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

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

问题描述:

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

I am implementing file saving functionality within a Qt application using C++.

我在寻找一种方法来检查

I am looking for a way to check to see if the selected file already exists before writing to it, so that I can prompt a warning to the user.

我使用 std :: ofstream

I am using an std::ofstream and I am not looking for a Boost solution.

#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。

I find this much more tasteful than trying to open a file if you have no immediate intentions of using it for I/O.