无类型文件
无类型文件是低级I/O通道,它主要用于直接访问磁盘文件,而不管文件的类型和结构。无类型文件的声明只使用保留字file,例如
var DataFile: file;
对无类型文件调用Reset和Rewrite过程时,允许用额外的参数指定用于数据传输的记录尺寸。由于历史原因(较早的Pascal),缺省的记录尺寸是128字节。记录的尺寸是1时,它仅作为一个特殊的值,用于精确反映任何文件的实际尺寸(记录不可再分是可能的,此时记录尺寸为1)。
除Read和Write外,所有用于类型文件的标准过程和函数也允许用于无类型文件。作为Read和Write的替代例程,BlockRead和BlockWrite用于高速数据传输。
下边是原形:
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.
例子
var
FromF, ToF: file;
NumRead, NumWritten: Integer;
Buf: array[1..2048] of Char;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(FromF, OpenDialog1.FileName);
Reset(FromF, 1); { Record size = 1 }
if SaveDialog1.Execute then { Display Save dialog box}
begin
AssignFile(ToF, SaveDialog1.FileName); { Open output file }
Rewrite(ToF, 1); { Record size = 1 }
Canvas.TextOut(10, 10, 'Copying ' + IntToStr(FileSize(FromF))
+ ' bytes...');
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
BlockWrite(ToF, Buf, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <> NumRead);
CloseFile(FromF);
CloseFile(ToF);
end;
end;
end;