Archive for 6月 16th, 2010

c++でのファイル読み込みテスト

ゲームプログラマになる前に覚えておきたい技術」を読んでいて、C++のファイル読み込みをやっていた。
Cの時でさえ、そんなにファイルいじったりしていなかったので、ちょっと自分でも書いてみる。
まぁ、写経的なコードになっちゃうんだけれども。

main.cpp

#include <iostream>

using namespace std;

bool readFile( char** buff, int* size, const char* filename );

int main()
{
	char *fBuff = 0;
	int fSize = 0;
	if ( readFile( &fBuff, &fSize, "test_dat.txt" ) ) {
		cout.write( fBuff, fSize );
	}

	delete[] fBuff;
	return 0;
}

fileRead.cpp

#include <fstream>

using namespace std;

bool readFile( char** buff, int* size, const char* filename )
{
	// 初期化
	*buff = 0;
	*size = 0;

	// ファイルストリームをインスタンス化しつつストリームオープン
	ifstream ifs( filename, ios::binary );

	// 失敗
	if ( !ifs ) { return false; }

	ifs.seekg( 0, ifstream::end ); // ファイルストリームを最後まで移動

	// 現在の読み込み位置(詰まるところサイズ)を取得
	// tellg()はpos_type型を返すので、実体はintでも一応キャスト
	*size = static_cast< int >( ifs.tellg() );

	ifs.seekg( 0, ifstream::beg );	// ファイルストリームを先頭へ

	// メモリ確保
	*buff = new char [ *size ];

	// ファイルの内容をメモリに読み込む
	ifs.read( *buff, *size );

	return true;
}

test_dat.txt

Hello.
And say goodbye.

で、結果。

% g++ -o test main.cpp fileRead.cpp
% ./test
Hello.
And say goodbye.

ちなみに、

delete[] *fBuff;

とても、

delete[] &fBuff;

としても怒られた。
ダブルポインタは大本の変数名だけ指定すれば良いんですかい?
メモリリークとかしないのか?
この前紹介した「OpenGLで作るiPhone SDKゲームプログラミング」では

ParticleSystem::~ParticleSystem()
{
	int i;

	for (i = 0; i < this->amount; ++i) {
		delete this->particle[i];
	}
	delete this->particle;
}

なんてコードがあったから、面倒くさいけど個別に解放しないとリークしちゃうのかと思った。
そうか、その配列内でさらにnewしているから個別に解放しているのか。
そうじゃない場合はそのまま解放して良い、と。
ポインタをもっとよく勉強せねば。。。

そんだけ。

Post to Twitter

, , ,

2 Comments

Bad Behavior has blocked 19 access attempts in the last 7 days.