Delphi 2010:如何将整个记录保存到文件中? [英] Delphi 2010: How to save a whole record to a file?
问题描述
我定义了一个记录,它有很多不同类型的字段(整数、实数、字符串……加上……数组"方面的动态数组).我想将它作为一个整体保存到一个文件中,然后能够将它加载回我的程序.我不想单独保存每个字段的值.文件类型(二进制或 ascii 或 ...)并不重要,只要 Delphi 可以将其读回记录即可.
I have defined a record which has lots of fields with different types (integer, real , string, ... plus dynamic arrays in terms of "array of ..."). I want to save it as a whole to a file and then be able to load it back to my program. I don't want to go through saving each field's value individually. The file type (binary or ascii or ...) is not important as long Delphi could read it back to a record.
您有什么建议吗?
推荐答案
只要不使用动态数组,就可以直接在流中加载和保存记录的内存.所以如果你使用字符串,你需要让它们固定:
You can load and save the memory of a record directly to and from a stream, as long as you don't use dynamic arrays. So if you use strings, you need to make them fixed:
type TTestRecord = record
FMyString : string[20];
end;
var
rTestRecord: TTestRecord;
strm : TMemoryStream;
strm.Write(rTestRecord, Sizeof(TTestRecord) );
您甚至可以一次加载或保存一组记录!
You can even load or save an array of record at once!
type TRecordArray = array of TTestRecord;
var ra : TRecordArray;
strm.Write(ra[0], SizeOf(TTestRecord) * Length(ra));
如果你想写动态内容:
iCount := Length(aArray);
strm.Write(iCount, Sizeof(iCount) ); //first write our length
strm.Write(aArray[0], SizeOf * iCount); //then write content
之后,您可以阅读它:
strm.Read(iCount, Sizeof(iCount) ); //first read the length
SetLength(aArray, iCount); //then alloc mem
strm.Read(aArray[0], SizeOf * iCount); //then read content
这篇关于Delphi 2010:如何将整个记录保存到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!