// 22_22-13.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <fstream>
#include <cstring>

using namespace std;

void dataput(int nbr);
int dataget(int nbr);
void datadsp();

struct Person {
	char name[28];
	int age;
} buf;

fstream fio;
fstream::pos_type end_pos;

int _tmain(int argc, _TCHAR* argv[])
{
	int i;

	// まずtmpfile.datファイルを作る
	fio.open("tmpfile.dat", ios_base::out | ios_base::binary);
	if (!fio) {
		cout << "ファイルをオープンできません\n";
		return 1;
	}
	
	cout << "-----データを格納する\n";
	strcpy_s(buf.name, "鈴木一郎");
	buf.age = 20;
	dataput(-1);
	strcpy_s(buf.name, "鈴木二郎");
	buf.age = 30;
	dataput(-1);
	strcpy_s(buf.name, "鈴木三郎");
	buf.age = 40;
	dataput(-1);
	fio.close();

	// ファイル入出力モードでオープンする
	fio.open("tmpfile.dat", ios_base::in | ios_base::out | ios_base::binary);
	if (!fio) {
		cout << "ファイルをオープンできません\n";
		return 1;
	}

	fio.seekg(0, ios_base::end);
	end_pos = fio.tellg();

	cout << "-----先頭からデータを読み込んで表示する\n";
	for (i = 0; ; i++) {
		if (!dataget(i)) {
			break;
		}
		cout << i << ": ";
		datadsp();
	}
	
	cout << "-----1番のデータを更新する\n";
	strcpy_s(buf.name, "渡辺五郎");
	buf.age = 55;
	dataput(1);

	cout << "-----先頭からデータを読み込んで表示する\n";
	for (i = 0; ; i++) {
		if (!dataget(i)) {
			break;
		}
		cout << i << ": ";
		datadsp();
	}
	fio.close();

	MessageBox(NULL, _T("Check Console Window"), L"MessageBox", MB_OK);

	return 0;
}

void dataput(int nbr)	// レコード書き込み。nbrが-1なら追加書き込み
{
	if (nbr == -1) {
		fio.seekp(0, ios_base::end);
	}
	else {
		fio.seekp(nbr * sizeof(buf), ios_base::beg);
		fio.write((char*)&buf, sizeof(buf));
		if (fio.tellg() > end_pos) {
			end_pos = fio.tellg();
		}
	}
}

int dataget(int nbr)
{
	fio.seekg(nbr * sizeof(buf), ios_base::beg);
	if (fio.tellg() >= end_pos) {
		return 0;
	}
	fio.read((char*)&buf, sizeof(buf));
	return 1;
}

void datadsp()
{
	cout << "name:" << buf.name << " age:" << buf.age << '\n';
}