このコードは、すべてのエラーをキャッチする必要があります。エラーが発生した場合は、ほとんどの場合、アクセス許可の問題です。ファイルを作成しているフォルダに読み書きできることを確認してください。
#include "stdafx.h"
#include <fstream>
#include <iostream>
bool CheckStreamErrorBits(const std::ofstream& ofile);
int _tmain(int argc, _TCHAR* argv[]) {
std::ofstream ofile("c:\\test.txt");
if(ofile.is_open()) {
CheckStreamErrorBits(ofile);
ofile << "this is a test" << std::endl;
if(CheckStreamErrorBits(ofile)) {
std::cout << "successfully wrote file" << std::endl;
}
}else {
CheckStreamErrorBits(ofile);
std::cerr << "failed to open file" << std::endl;
}
ofile.close();
return 0;
}
//return true if stream is ok. return false if stream has error.
bool CheckStreamErrorBits(const std::ofstream& ofile) {
bool bError=false;
if(ofile.bad()) {
std::cerr << "error in file stream, the bad bit is set" << std::endl;
bError=true;
}else if(ofile.fail()) {
std::cerr << "error in file stream, the fail bit is set" << std::endl;
bError=true;
}else if(ofile.eof()) {
std::cerr << "error in file stream, the eof bit is set" << std::endl;
bError=true;
}
return !bError;
}
更新: Windows 7 Enterprise でコードをテストしたところ、最初は失敗しました (失敗ビットが設定されていました)。次に、ユーザー アカウント制御 (UAC) をオフにして再度テストしたところ、ファイルが書き込まれました。それはおそらくあなたが見ているのと同じ問題です。UAC をオフにするには、次の場所に移動します。
コントロール パネル (小さなアイコンで表示) | ユーザー アカウント | ユーザー アカウント制御の設定を変更します。[通知しない] に設定し、[OK] ボタンをクリックします。変更を有効にするには、再起動する必要があります。
UAC をオンにして動作させる方法に興味があります。調べてみます。