Ric*_*ico 64
这是我最喜欢的折叠功能之一,我可以随时使用它.
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果您没有立即将其用于I/O,我发现这比尝试打开文件更有品味.
ret*_*n 0 39
bool fileExists(const char *fileName)
{
ifstream infile(fileName);
return infile.good();
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这种方法是最短且最便携的方法.如果使用不是很复杂,这是我想要的.如果您还想提示警告,我会在主要部分进行.
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
Run Code Online (Sandbox Code Playgroud)
请注意,如果是现有文件,则会以随机访问模式打开它.如果您愿意,可以关闭它并以追加模式或截断模式重新打开它.
对于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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
也可以看看std::error_code
。
如果您想检查正在写入的路径是否实际上是常规文件,请使用std::filesystem::is_regular_file
.
归档时间: |
|
查看次数: |
71185 次 |
最近记录: |