ゲームが作れるようになるまでがんばる日記

ゲーム制作のことを中心にゲームに関することを書いています

ファイル読み込み

C++でファイルを読み込むにはifstreamを使えばよい。
ファイルを読み込む処理は次のような感じ。

#include <iostream>
#include <fstream>
using namespace std;

char* openFile( const char* name, int* fileSize )
{
    ifstream inputFile( name, ifstream::binary );
    if ( !inputFile.is_open() ) { return NULL; }
    inputFile.seekg( 0, ifstream::end );
    *fileSize = static_cast<int>( inputFile.tellg() );
    inputFile.seekg( 0, ifstream::beg );
    char* buff = new char[ *fileSize ];
    inputFile.read( buff, *fileSize );

    return buff;
}

int main()
{
    const char fname[] = "test.txt";
    int fileSize = 0;
    char* buff = openFile( fname, &fileSize );
    if (buff) {
        cout.write( buff, fileSize );
        delete[] buff;
    }
    else {
        cout << "file not found." << endl;
    }
}

まずifstreamのコンストラクタでファイル名を渡してバイナリーモードでファイルを開く。正しくファイルが開けたかどうかはis_open()でチェック。ファイル位置を最後に移動してサイズを取得。ファイル位置を先頭に戻してファイルを読み込む。このあたりはC言語のファイル読み込みと同じ。


参考文献:ゲームプログラマになる前に覚えておきたい技術 - 秀和システム あなたの学びをサポート