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

, , ,

  1. #1 by Hashim Armstrong on 2011 年 5 月 1 日 - 1:23 AM

    hello admin. i opened up my mail today and kept following the links from page to page and somehow ended up here on %BLOGINTITLE%.. i have been reading your posts since then and i like the way you write. are you currently on twitter?? simply because i would really like to follow you and get notified any time you post on your blog here. i am trying to read all of your posts and i’m enjoying them a great deal. thanks a whole lot for putting up a nice informative blog. Thank you.

  2. #2 by Kennan Cobb on 2011 年 5 月 2 日 - 7:33 PM

    hello %BLOGINTITILE% owner. i want to say that %BLOGINTITLE% is genuinely nice and the post was excellant. it seems that you have got many visitors on your blog. i’ve started off blogging couple of weeks back and i am still struggling to get any individuals to my blog. i would genuinely love it if you ever go to my blog and comment on the posts. although the blog is completely new, still there’s some great content on it. i hope you’ll enjoy reading it. Cheers Kennan Cobb

Comments are closed.

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