// 22_22-12.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sstream>
#include <fstream>

using namespace std;

void disp(char *p, int n)
{
	while (n--) {
		cout << *p++;
	}
	cout << '\n';
}

int _tmain(int argc, _TCHAR* argv[])
{
	ofstream fout;
	fstream fio;
	fstream::pos_type mypos;
	char cc[40] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	// まずtmpfile.txtファイルを作る
	fout.open("tmpfile.txt", ios_base::out | ios_base::binary);
	if (!fout) {
		return 1;
	}
	fout << cc;
	fout.close();

	// 同じファイルを入出力モードで開く
	fio.open("tmpfile.txt", ios_base::in | ios_base::out | ios_base::binary);
	if (!fio) {
		return 1;
	}

	cout << "-----オープン直後に26文字読み込む\n";
	fio.read(cc, 26);
	disp(cc, 26);

	cout << "-----先頭(0〜)から3文字目指定し5文字読み込む\n";
	fio.seekg(3, ios_base::beg);
	fio.read(cc, 5);
	disp(cc, 5);

	cout << "-----終端から10文字目を指定し5文字読み込む\n";
	fio.seekg(-10, ios_base::end);
	fio.read(cc, 5);
	disp(cc, 5);

	cout << "-----先頭から5文字目指定し1234を書き込む\n";
	fio.seekp(5, ios_base::beg);
	fio << "1234";

	cout << "-----続いてwrite関数で5678を書き込む\n";
	fio.write("5678", 4);

	cout << "-----現在位置から4文字後にabcdを書き込む\n";
	fio.seekg(4, ios_base::cur);
	fio << "abcd";

	cout << "-----現在位置(abcd書き込みの次)をmyposに保存する\n";
	mypos = fio.tellp();
	cout << "mypos=" << mypos << '\n';

	cout << "-----先頭から26文字を読む\n";
	fio.seekg(0, ios_base::beg);
	fio.read(cc, 26);
	disp(cc, 26);

	cout << "-----mypos位置を指定し4文字読み込む\n";
	fio.seekg(mypos);
	fio.read(cc, 4);
	disp(cc, 4);

	fio.close();

	MessageBox(NULL, _T("Check Console Window"), L"MessageBox", MB_OK);

	return 0;
}

