Re: Writing Binary Files with TFileStream



Robert Kilroy wrote:
Here is the function to READ: (Which works just fine)
var
	fid : Word;
	l : Byte;
	fieldid, value : String;
	FS : TFileStream;
try
	FS := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone);
	tData.Clear;
	while (FS.Position < FS.Size) do
	begin
		FS.Read(fid, SizeOf(fid));
		if fid = $ffff then break;
		fieldid := IntToStr(fid);
		FS.Read(l, 1);
		SetLength(value, l);
		if l > 0 then
			FS.Read(value[1], l);

When you read the string length, you read one byte.

Here is the WRITE function:
var
	FS : TFileStream;
	i : Integer;
	l : LongInt;
	x, e : Word;
	brwFieldID, brwValue : String;
begin
	try
	if FileExists(fname) then
		FS := TFileStream.Create(fname, fmOpenWrite)
	else
		FS := TFileStream.Create(fname, fmCreate);
	for i := 0 to tData.Count - 1 do
	begin
		brwFieldID := pntData.Names[i];
		brwValue := pntData.ValueFromIndex[i];
		x := StrToInt(brwFieldID);
		FS.Write(x, SizeOf(x));
		l := length(brwValue);
		FS.Write(l, SizeOf(l));
                FS.Write(brwValue[1], l);

When you write the string length, you write four bytes.

You were also more careful about empty strings in your reading function than you are in your writing function.

--
Rob
.



Relevant Pages

  • Re: Working with very large text files
    ... Doug, Whether you use TFileStream or plain "file" type, I think ... dig in and define a reader class. ... so that the result string need not be reallocated each time. ...
    (borland.public.delphi.thirdpartytools.general)
  • Re: Reading binary files of irregular format with TMemoryStream
    ... I check the bytes for characters by copying from one string to another, ... FieldId: word; ... FieldStrIn, FieldStrOut: string; ... FS:= TFileStream.Create(FPN, fmOpenRead or {fmSharCompat or} ...
    (comp.lang.pascal.delphi.misc)
  • Stream access to a text file - skipping first 21 bytes
    ... If I use a TFileStream to read the beginning of a text file, ... Same thing happens if I use a TMemoryStream and ... procedure TForm1.ShowHex(Fn: string); ... Another strange thing (separate problem) is that I get hex representation of ...
    (borland.public.delphi.language.objectpascal)
  • Re: How to search for a specific string in a txt file (FindComponent?)
    ... > I need to find this string and then change it into something else. ... > I've tried using the FindComponent but no success. ... Input:=TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite); ...
    (comp.lang.pascal.delphi.misc)
  • Re: Text file question
    ... >into memory when only the last line is of any interest. ... Then copy the last 300 or so bytes from the end of a TFileStream into another a ... load that stream into a stringlist and take the last String ... Alan Lloyd ...
    (alt.comp.lang.borland-delphi)