Board index » delphi » Reading and writing records to a file

Reading and writing records to a file

Hi!

For some time ago I programmed in VB. There was some nice functions that you
could use to read and write records to a file.

The problem I have is that I want to read a record from a file, and replace
the record without writing the whole file from the top down.

Any way to do this?
(I dont want to use BDE to do this)

-Geir-
g...@royal.no

 

Re:Reading and writing records to a file


On Sun, 11 Jan 1998 20:20:52 +0100, "Geir Bratlie" <ro...@online.no>
wrote:

Quote
>Hi!

>For some time ago I programmed in VB. There was some nice functions that you
>could use to read and write records to a file.

>The problem I have is that I want to read a record from a file, and replace
>the record without writing the whole file from the top down.

>Any way to do this?
>(I dont want to use BDE to do this)

Yes, here's an example (from memory) that assumes a file is in the
same directory as the executable:

  var
    I: Integer;
    Path: string;
    F: file of YourRec;
  begin

    Path := ExtractFilePath(ExeName);

    if FileExists(Path + 'Filename') then
    try
      AssignFile(F, Path + 'FileName');
      Reset(F);
      if (FileSize(F) > 0) then for I := 0 to (FileSize(F) - 1) do
      begin
        Read(F, RecVariable);
        if (RecVariable.Field = TheOneYouWant) then
        begin
          Seek(F, I);  {This returns position to record just read}
          {Write new data to record fields}
        end;
      end;
    finally
      CloseFile(F);
    end

If you wish to remove a record entirely (not just write new data to
it) then there is no way around moving records up one position, and
truncating the file; the code is just as straightforward, but slightly
different.

Simon R Knight

Re:Reading and writing records to a file


Quote
Geir Bratlie wrote:

> Hi!

> For some time ago I programmed in VB. There was some nice functions that you
> could use to read and write records to a file.

> The problem I have is that I want to read a record from a file, and replace
> the record without writing the whole file from the top down.

        Have you tried simply opening it as "file of TYourRecord" and
using Read and Write? See the docs on "Read procedure" - also see
"Seek procedure". (If it's a file of TWhatever then Seek seeks the
n-th whatever in the file, exactly what you want.)

        A lot of people feel that using streams (maybe TFileStream
here) is a lot nicer.

--
David Ullrich

sig.txt not found

Other Threads