C++ std::ofstream,写入前检查文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4316442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
std::ofstream, check if file exists before writing
提问by cweston
I am implementing file saving functionality within a Qtapplication using C++.
我正在使用 C++在Qt应用程序中实现文件保存功能。
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.
我正在寻找一种方法来检查所选文件是否在写入之前已经存在,以便我可以向用户提示警告。
I am using an std::ofstream
and I am not looking for a Boostsolution.
我正在使用std::ofstream
并且我不是在寻找Boost解决方案。
回答by Rico
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 find this much more tasteful than trying to open a file if you have no immediate intentions of using it for I/O.
如果您没有立即将其用于 I/O 的意图,我发现这比尝试打开文件更有品味。
回答by return 0
bool fileExists(const char *fileName)
{
ifstream infile(fileName);
return infile.good();
}
This method is so far the shortest and most portable one. If the usage is not very sophisticated, this is one I would go for. If you also want to prompt a warning, I would do that in the main.
这种方法是迄今为止最短、最便携的方法。如果用法不是很复杂,这是我会去的。如果您还想提示警告,我会在 main.js 中这样做。
回答by HighCommander4
fstream file;
file.open("my_file.txt", ios_base::out | ios_base::in); // will not create file
if (file.is_open())
{
cout << "Warning, file already exists, proceed?";
if (no)
{
file.close();
// throw something
}
}
else
{
file.clear();
file.open("my_file.txt", ios_base::out); // will create if necessary
}
// do stuff with file
Note that in case of an existing file, this will open it in random-access mode. If you prefer, you can close it and reopen it in append mode or truncate mode.
请注意,对于现有文件,这将以随机访问模式打开它。如果您愿意,可以关闭它并以追加模式或截断模式重新打开它。
回答by Bhagyesh Dudhediya
One of the way would be to do stat()
and check on errno
.
A sample code would look look this:
一种方法是执行stat()
并检查errno
.
示例代码如下所示:
#include <sys/stat.h>
using namespace std;
// some lines of code...
int fileExist(const string &filePath) {
struct stat statBuff;
if (stat(filePath.c_str(), &statBuff) < 0) {
if (errno == ENOENT) return -ENOENT;
}
else
// do stuff with file
}
This works irrespective of the stream. If you still prefer to check using ofstream
just check using is_open()
.
Example:
这与流无关。如果您仍然更喜欢使用检查,ofstream
只需检查使用is_open()
。
例子:
ofstream fp.open("<path-to-file>", ofstream::out);
if (!fp.is_open())
return false;
else
// do stuff with file
Hope this helps. Thanks!
希望这可以帮助。谢谢!
回答by Roi Danton
With std::filesystem::exists
of C++17:
使用std::filesystem::exists
C++17:
#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.
}
}
}
See also std::error_code
.
In case you want to check if the path you are writing to is actually a regular file, use std::filesystem::is_regular_file
.
如果您想检查您写入的路径是否实际上是一个常规文件,请使用std::filesystem::is_regular_file
.