关于记录文件的操作?(100分)

  • 主题发起人 主题发起人 liaolion
  • 开始时间 开始时间
L

liaolion

Unregistered / Unconfirmed
GUEST, unregistred user!
我在Delphi中建立了一个记录,记录中包含的变长的字符串(如果用定长的字符串,那么记录
多了之后,写到记录文件中会非常大),所以每个记录的Size不是固定的。这样的话,我怎样
才能够一个一个的读出、插入、删除记录文件中的记录?

 
type

procedure BlockRead(var F: File; var Buf; Count: Integer [; var AmtTransferred: Integer]);

Description

F is an untyped file variable, Buf is any variable, Count is an expression of type Integer, and AmtTransferred is an optional variable of type Integer.

BlockRead reads Count or fewer records from the file F into memory, starting at the first byte occupied by Buf. The actual number of complete records read (less than or equal to Count) is returned in AmtTransferred.

The entire transferred block occupies at most Count * RecSize bytes. RecSize is the record size specified when the file was opened (or 128 if the record size was not specified).

If the entire block was transferred, AmtTransferred is equal to Count.

If AmtTransferred is less than Count, ReadBlock reached the end of the file before the transfer was complete. If the file's record size is greater than 1, AmtTransferred returns the number of complete records read.

If AmtTransferred isn't specified, an I/O error occurs if the number of records read isn't equal to Count. If the $I+ compiler directive is in effect, errors raise an EInOutError exception.
 
每保存一条记录时,在记录前面先保存后面数据块的长度,其他容易。
 
变长的记录是不能按记录保存的,你得自己一点点地写。
按记录读写速度较快,如果想利用它来提高性能,有个变通的方法,就是另写一个记录,
把会变长的部分去掉,改为其大小,其它跟原记录一样。变长的部分如果是字符串可
以批量读写。
例如:
TMyRec=Record
ID: Integer;
Prop1: Double;
Data: string;
end;
其中Data是变长的,则定义
TMyRecSave=Record
ID: Integer;
Prop1: Double;
DataLen: Integer;
end;
这是个定长的记录,后面跟着保存Data内容。

文件中的插入、删除操作是很困难的,需要整片的挪动内容,对大文件非常不利。
一般做法是追加和改写,删除则可以通过打上标识实现,例如上例中把ID改为-1。
 
这是一个数据库存贮问题,
我们还是从数据库的处理谈起
数据库字段有CHAR(XXX),VARCHAR,TEXT这些类型
他们都是存贮的字符串
但是CHAR是定长,另外两种不定长

他们如何做的呢?他们采用的方法其实都是MEMO类,就是采用定长和非定长分开存贮.

我们先定义一个记录

TMYDATASTORE=RECORD
ID:INTEGER;
PROP1:DOUBLE;
STRPOS:INTEGER;
STRLEN:INETEGR;
END;
这样我们可以在一个记录文件中用TMYDATASTORE结构记录存贮定长的内容

而在另外一个文件中存贮非定长的内容,也就是变长的字符串.
而STRPOS就是其字符串在另外一个文件中的偏移,
STRLEN就是字符串的长度.

这样做,我们就可以很容易的对文件记录进行添加和删除操作,例如删除就设置ID为0,添加
就可以直接加到最后,当然,也可以查找是否有ID为0的空处.

倘若需要整理,我们就做一个PACK工具,重新组织一个紧缩的MEMO文件,并且修改掉定长
记录文件中相对的STRPOS
 
做个文件链表表吧,很方便,假如都是从头到尾,而不需要定位到某条记录的话(如果有
索引速度也还可以),性能还是可以的。

JG=record
prev:longint;//上一个节点的位置
next:longint;//下一个节点的位置
len:longint;//本节点长度
del:boolean;//删除标志
end;

prev:JG;//前一个节点
p:JG//当前节点

insert:
p.prev:=prev的位置;
prev.next.prev:=p位置;
p.next:=prev.next;
prev.next:=p的位置;

delete:
prev.next:=p.next;
p.next.prev:=p.prev;
p.del:=true;

read:
从文件头开始读吧

pack://压缩掉被标为Del的节点

权你还是看看清华的那本《数据结构》很经典的书,对你会大有益处的
祝你成功;)
 
to 苦虫,
清华的《数据结构》有很多版本。是哪一本,谁写的,能不能说详细一点?
 
后退
顶部