C++読み書きファイルサンプルコード


ファイルを書く
#include 
#include   //       
using namespace std;

ofstream out("C:/Users/l21599/Desktop/out.txt");
if (out.is_open())
{
    //      
	out << "This is a line.
"
; out << "This is another line.
"
; out.close(); } return 0;

ファイルを読む
#include 
#include 
using namespace std;

char buffer[256];
ifstream in("C:/Users/l21599/Desktop/out.txt");
if (!in.is_open())
{ 
	cout << "Error opening file"; 
	exit(1);
}
while (!in.eof())
{
    //      
	in.getline(buffer, 100);
	cout << buffer << endl;
}
in.close();
return 0;
eof()は、ファイルの末尾に到達したか否かを判断するための状態フラグ関数である.他にも次のものがあります.
  • bad()読み書き中にエラーが発生した場合はtrueを返します.たとえば、書き込み状態ではないファイルに書き込みを行う場合や、書き込みするデバイスに空き容量がない場合などです.
  • fail()はbad()と同じ場合にtrueを返すほか、フォーマットエラーを加えた場合にもtrueを返し、例えば整数を読み込もうとしてアルファベットを1文字得た場合にも返します.
  • good()これは最も一般的です.以上のいずれかの関数を呼び出してtrueを返すと、この関数はfalseを返します.