本篇是创建游戏内核(3)【C风格版】的续篇,关于该内核的细节说明请参考创建游戏内核(4)。
//-----------------------------------------------------------------------------
// Write mal_data into file.
//-----------------------------------------------------------------------------
BOOL save_data_to_file(pcstr filename, const void_ptr data, ulong size)
{
FILE* fp;
if(data == NULL || size == 0)
return FALSE;
// open file, write size and mal_data.
if((fp = fopen(filename, "wb")) == NULL)
return FALSE;
fwrite(&size, 1, 4, fp);
fwrite(data, 1, size, fp);
fclose(fp);
return TRUE;
}
//-----------------------------------------------------------------------------
// Load mal_data from file.
//-----------------------------------------------------------------------------
BOOL load_data_from_file(pcstr filename, void_ptr_ref data, ulong_ref size)
{
FILE* fp;
if((fp = fopen(filename, "rb")) == NULL)
return FALSE;
// read in size and mal_data
ulong data_size;
char_ptr mal_data;
fread(&data_size, 1, 4, fp);
if((mal_data = (char_ptr) malloc(data_size)) == NULL)
return FALSE;
memset(mal_data, 0, sizeof(data_size));
fread(mal_data, 1, data_size, fp);
fclose(fp);
data = mal_data;
size = data_size;
return TRUE;
}
测试代码:
/*************************************************************************
PURPOSE:
Test for read and wirte data from file.
*************************************************************************/
#include "core_common.h"
#include "core_framework.h"
#include "core_tool.h"
// a structure to contain a name
struct NAME
{
char name[32];
};
BOOL game_init()
{
const int data_size = 64;
// create the data package (w/64 bytes) and get the pointer, casting it to an NAME structure type.
NAME* names = (NAME*) malloc(data_size);
// since there are 64 bytes total, and each name uses 32 bytes, then I can have 2 names stored.
strcpy(names[0].name, "loved");
strcpy(names[1].name, "day");
const char* filename = "names.data";
// save the names to disk
save_data_to_file(filename, names, data_size);
// destroy data
free(names);
DWORD load_size;
// load the names from disk, size will equal 64 when the load function returns.
load_data_from_file(filename, (void_ptr_ref)names, load_size);
// display the names
MessageBox(NULL, names[0].name, "1st name", MB_OK);
MessageBox(NULL, names[1].name, "2nd name", MB_OK);
free(names);
return TRUE;
}
BOOL game_frame()
{
return TRUE;
}
BOOL game_shutdown()
{
return TRUE;
}
//--------------------------------------------------------------------------------
// Main function, routine entry.
//--------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE inst, HINSTANCE pre_inst, LPSTR cmd_line, int cmd_show)
{
if(! build_window(inst, "MainClass", "MainWindow", WS_OVERLAPPEDWINDOW, 0, 0, 800, 600))
return FALSE;
run_game(game_init, game_frame, game_shutdown);
return 0;
}