Delphi 2010:如何将整个记录保存到文件? [英] Delphi 2010: How to save a whole record to a file?

查看:291
本文介绍了Delphi 2010:如何将整个记录保存到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个记录,它有很多不同类型的字段(整数,实数,字符串,...加上动态数组的数组...)。
我想将它保存为一个整体到一个文件,然后可以加载到我的程序。我不想单独保存每个字段的值。
文件类型(二进制或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));

如果您想编写动态内容,请执行以下操作:

In case you want to write dynamic content:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆