Windows CE 3.0Pocket PC 2002Windows MobileVisual C++ 7.0Windows 2000Visual C++ 6.0Windows XP移动应用中级开发Visual StudioWindowsC++
内存映射文件和平表原始类型。






3.11/5 (18投票s)
2003年4月7日

211325

644
用于持久化平表数据的 C++ 类。
引言
假设您需要在应用程序中将一些结构的数组存储和读取到硬盘上或从硬盘上读取。
例如:您可能有一个如下结构
struct record { char first_name[32]; char last_name[64]; record() { first_name[0] = 0; last_name[0] = 0; } void set(const char* first, const char *last) { strncpy(first_name, first, sizeof(first_name)-1); strncpy(last_name, last, sizeof(last_name)-1); } };
并且您希望持久化一个这样的数组。
与其使用昂贵(在许多方面)的经典数据库解决方案,您可以编写以下代码
#include "tl_mm_file.h" int main(int argc, char* argv[]) { tool::table<record> tbl; /* writing/creating table of "record"s */ tbl.open("c:/test.tbl",true); tbl[0].set("Andrew","Fedoniouk"); tbl[1].set("Allan","Doe"); tbl[2].set("Monica","Lester"); tbl.close(); /* reading it */ tbl.open("c:/test.tbl"); for(unsigned int i = 0; i < tbl.total(); i++) printf("%s %s\n", tbl(i).first_name, tbl(i).last_name ); tbl.close(); return 0; }
您只需要在项目中包含 mm_file.h 和 mm_file.cpp,就完成了。
优点
- 简单快捷。这种访问持久化数据的方法几乎没有时间开销来打开/关闭数据集,并消除了对中间缓冲区(又名“当前记录”)的需求。
- 它提供对表中记录的直接随机访问。
- 紧凑且自给自足的实现。
缺点
- 仅支持固定大小的结构。
- 如果需要,应单独实现按键(哈希表、B 树等)访问。(如果需要)