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

2024-08-14C/C++开发问题
28

本文介绍了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 并且我不是在寻找 Boost 解决方案.

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

推荐答案

这是我最喜欢的隐藏功能之一,我手头有很多用途.

This is one of my favorite tuck-away functions I keep on hand for multiple uses.

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

这篇关于std::ofstream,写入前检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6