VFP封装结构类型示例(四) [结]
VFP封装结构类型,作为示例最后探讨一下数据结构与链表。VFP 的 DBF 也是应用数据结构与链表的产物,学VFP的对这方面了解一下可以加深对 DBF 的理解,也可以设计其他格式的数据文件。
相关文件
StructClass_demo.rar
(7.87 KB)
程序代码:
CLEAR cDefPath = ADDBS(JUSTPATH(SYS(16))) SET DEFAULT TO (cDefPath) #INCLUDE apiFuns.h SET PROCEDURE TO apiFuns.prg, StructClass.prg ADDITIVE LoadApi() ds = CREATEOBJECT("数据结构") ds.create() dt = CREATEOBJECT("数据表") bufSize = ds.size pBuffer = myMalloc(bufSize) head = 0 && 头记录指针 last = 0 && 尾记录指针 filename = cDefPath + "test.dat" load_data(filename) add_data("张三", 1, 18, 170) add_data("李四", 2, 22, 175) list_data() save_data(filename) SET PROCEDURE TO CLEAR ALL RETURN DEFINE CLASS 数据结构 as STRUCT_CLASS PROCEDURE init this.stInit("name", "C",10) this.stInit("num1", "U",1) this.stInit("num2", "I",2) this.stInit("num3", "I",4) ENDPROC ENDDEFINE DEFINE CLASS 数据表 as STRUCT_CLASS PROCEDURE init(ds) this.stInit("数据记录", "C",17) this.stInit("next", "U",4) ENDPROC ENDDEFINE FUNCTION add_data(name, num1, num2, num3) LOCAL ptr ptr = dt.create() ds.setValue("name", name, ptr) ds.setValue("num1", num1, ptr) ds.setValue("num2", num2, ptr) ds.setValue("num3", num3, ptr) dt.setValue("next", 0, ptr) IF last != 0 dt.setValue("next", ptr, last) ENDIF IF head == 0 head = ptr ENDIF last = ptr RETURN last ENDFUNC FUNCTION load_data(filename) IF !FILE(filename) RETURN 0 ENDIF LOCAL fp, ptr fp = myFOpen(filename, "rb") IF fp == 0 RETURN 0 ENDIF head = 0 last = 0 IF apiFRead(pBuffer,bufSize,1,fp) == 1 head = dt.create() apiMemcpy_s(head, bufSize, pBuffer, bufSize) dt.setValue("next", 0, head) last = head ENDIF DO WHILE apiFRead(pBuffer,bufSize,1,fp) == 1 ptr = dt.create() apiMemcpy_s(ptr, bufSize, pBuffer, bufSize) dt.setValue("next", 0, ptr) dt.setValue("next", ptr, last) last = ptr ENDDO apiFClose(fp) RETURN head ENDFUNC FUNCTION save_data(filename) LOCAL fp, ptr fp = myFOpen(filename, "wb") IF fp == 0 RETURN 0 ENDIF ptr = head DO WHILE ptr != 0 apiFWrite(ptr, bufSize, 1, fp) ptr = dt.getValue("next", ptr) ENDDO apiFClose(fp) RETURN 1 ENDFUNC FUNCTION list_data() LOCAL ptr ptr = head DO WHILE ptr != 0 ? ds.getValue("name", ptr) ?? ds.getValue("num1", ptr) ?? ds.getValue("num2", ptr) ?? ds.getValue("num3", ptr) ptr = dt.getValue("next", ptr) ENDDO ENDFUNC