德尔福2010 : How to save a whole record to a file?

标签 delphi file-io delphi-2010

我定义了一个记录,其中包含许多不同类型的字段(整数、实数、字符串……加上“数组……”的动态数组)。 我想将其作为一个整体保存到一个文件中,然后能够将其加载回我的程序中。我不想单独保存每个字段的值。 文件类型(二进制或 ascii 或...)并不重要,只要 Delphi 可以将其读回记录即可。

你有什么建议吗?

最佳答案

只要不使用动态数组,您就可以直接从流中加载和保存记录的内存。所以如果你使用字符串,你需要将它们固定:

type TTestRecord = record 
  FMyString : string[20]; 
end; 

var 
  rTestRecord: TTestRecord;
  strm : TMemoryStream; 

strm.Write(rTestRecord, Sizeof(TTestRecord) );

您甚至可以一次加载或保存记录数组!

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

关于德尔福2010 : How to save a whole record to a file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3820996/

相关文章:

c - 如何将c中的数据类型byte []转换为delphi?

delphi - 如何说服内存管理器释放未使用的内存

json - SuperObject - 使用 "."文字解析字段名中的数据

Java - 从jar目录中读取文件

delphi - Windows 服务 + 在系统托盘中运行应用程序

delphi - 将Firebird UDF库更新到Delphi 2010

windows - 如何使其他应用程序隐藏窗口从我的应用程序可见?

java - Java 中 File.exists() 的替代方案

python - 如果我在 Python 3 中将文件截断为零,我是否还需要寻找零位置?

delphi - Delphi-如何监控网络