我正在使用C++在Qt应用程序中实现文件保存功能。
我正在寻找一种在写入文件之前检查所选文件是否已经存在的方法,以便可以提示用户警告。
我正在使用std :: ofstream,而不是寻找Boost解决方案。
我正在寻找一种在写入文件之前检查所选文件是否已经存在的方法,以便可以提示用户警告。
我正在使用std :: ofstream,而不是寻找Boost解决方案。
这是我最喜欢的藏在口袋里的函数之一,我经常用它来实现多种功能。
#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;
更加简洁。 - Matt Phillips!= 1
而不是!= -1
之外,它为什么不会产生相同的效果呢? - Gurgadurgenstruct
关键字有什么原因吗?除非我不知道C头文件内部存在某些名称冲突,否则这并不是必需的。 - Lightness Races in Orbitbool fileExists(const char *fileName)
{
ifstream infile(fileName);
return infile.good();
}
这个方法到目前为止是最短和最具可移植性的方法。如果使用不是非常复杂,这是我会选择的方法。如果您还想提示警告,则应在主函数中执行。
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()
。 - HighCommander4使用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::error_code
。
如果你想检查你要写入的路径是否为普通文件,请使用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