A
A
Anton Savchenko2015-06-02 00:34:44
Delphi
Anton Savchenko, 2015-06-02 00:34:44

Working with files in Delhi. How not to go crazy?

I have two procedures.
The first one adds an entry to the file:

Procedure Add_Rec(app:RecType;way:string);
    var
      f:FileType;
      recc:RecType;
      i:integer;
    begin
      Assign(f,way);
      reset(f);
      while not(Eof(f)) do
        begin
          read(f,recc);
          inc(i);
        end;
      close(f);
      rewrite(f);
      writeln('---',i);
      Seek(f,i);
      write(f,app);
      close(f);
    end;

And do it like this:
reset(f);
      while not(Eof(f)) do
        begin
          read(f,recc);
          inc(i);
        end;
      close(f);

instead of using Seek(f, FileSize(f)) I have to, since FileSize always returns 0 (it is in this procedure, it works fine in the rest)
The second one displays the contents of the file:
procedure output(way:string);
    var
      f:filetype;
      rec:RecType;
      i:integer;
    begin
      assign(f,way);
      reset(f);
      if filesize(f) > 0 then
        for i:=1 to filesize(f) do
          begin
            read(f,rec);
            writeln('Запись ',i,':');
            writeln('  Марка:    ',rec.model);
            writeln('  Цвет:     ',rec.color_car);
            writeln('  Гос. номер:    ',rec.state_number);
            writeln('  Владелец: ',rec.owner);
          end
      else
        writeln('Файл пуст.');
      close(f);
    end;

Here is the result: d3a0ef767c024e3abbf40475ef5a31e4.jpg
All entries except the last one become empty. What's happening? I can't understand at all.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Puma Thailand, 2015-06-02
@Lapital

rewrite rubs the previous contents of the file, use append

Z
zed, 2015-06-02
@zedxxx

Discover TFileStream, TMemoryStream and TStringStream - this is exactly what Delphi uses to work with files.
Required reading:
Serialization - Pascal-style files (this is how you do it now)
Serialization - data streams (and this is about how to do it in the Delphi world)

V
Vladimir Martyanov, 2015-06-02
@vilgeforce

See debugger.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question