C++ を使用してQtアプリケーション内にファイル保存機能を実装しています。
ユーザーに警告を表示できるように、選択したファイルに書き込む前に、そのファイルが既に存在するかどうかを確認する方法を探しています。
を使用していますが、 Boostソリューションstd::ofstream
は探していません。
これは、複数の用途のために手元に置いておくお気に入りのタックアウェイ機能の 1 つです。
#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 にすぐに使用するつもりがない場合にファイルを開こうとするよりも、はるかに上品だと思います。
bool 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
既存のファイルの場合、ランダム アクセス モードで開くことに注意してください。必要に応じて、それを閉じて、追加モードまたは切り捨てモードで再度開くことができます。
試す::stat()
( で宣言<sys/stat.h>
)
方法の 1 つは、実行し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
お役に立てれば。ありがとう!