std::ofstream, check if file exists before writing(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,写入前检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::ofstream,写入前检查文件是否存在
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
