【发布时间】:2011-05-18 00:24:22
【问题描述】:
我正在使用 C++ 在 Qt 应用程序中实现文件保存功能。
我正在寻找一种在写入之前检查所选文件是否已经存在的方法,以便向用户提示警告。
我正在使用std::ofstream,我不是在寻找 Boost 解决方案。
【问题讨论】:
标签: c++ stream std fstream ofstream
我正在使用 C++ 在 Qt 应用程序中实现文件保存功能。
我正在寻找一种在写入之前检查所选文件是否已经存在的方法,以便向用户提示警告。
我正在使用std::ofstream,我不是在寻找 Boost 解决方案。
【问题讨论】:
标签: c++ stream std fstream ofstream
这是我最喜欢的隐藏功能之一,我可以随时使用以供多次使用。
#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 的意图,我发现这比尝试打开文件更有品味。
【讨论】:
return stat(filename.c_str(), &buf) != 1; 更紧凑。
!= 1 而不是 @987654324 的事实@,为什么不会有同样的效果?
struct关键字的理由吗?在 C++ 中没有必要,除非 C 头文件中存在一些我不知道的名称冲突?
bool fileExists(const char *fileName)
{
ifstream infile(fileName);
return infile.good();
}
这种方法是迄今为止最短且最便携的方法。如果用法不是很复杂,这是我会选择的。如果你也想提示一个警告,我会在 main 中这样做。
【讨论】:
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
请注意,如果是现有文件,则会以随机访问模式打开它。如果您愿意,可以将其关闭并以追加模式或截断模式重新打开。
【讨论】:
std::filesystem::exists(),或者除非是 stat()。
std::filesystem,您可以使用POSIX API 中的stat() 函数(Windows 也支持)
试试::stat()(在<sys/stat.h>中声明)
【讨论】:
使用 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::filesystem::is_regular_file。
【讨论】:
其中一种方法是执行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
}
这与流无关。如果您仍然喜欢使用ofstream 进行检查,请使用is_open() 进行检查。
示例:
ofstream fp.open("<path-to-file>", ofstream::out);
if (!fp.is_open())
return false;
else
// do stuff with file
希望这会有所帮助。 谢谢!
【讨论】: