Hi everybody,

I have a project to do for the college, which has to insert, read, delete and modify records in a binary file (a address book or something else). I don't know yet how I'll do to alter the records. Let's suppose the I have the program below:

program teste;
uses CRT;
type
reg = record
id:integer;
nome:string[30];
end;

var
arquivo: file of reg;
dados:reg;
begin
end.

The user will enter the id he wants to alter, i have done it this way, but it truncate the file at the current position:

while not eof(arquivo) do
begin
     read(arquivo,dados);
     if (dados.id = new) then
     begin
          dados.id:=new;
          write(arquivo,dados);
          break;
     end;
end;

Could somebody help me with this?

Thanks in advance.

Here is some partial code to you can use for reference.

Program SeekTest; {This program tests a binary file}

(* *)
type
   RegRec = record
      number: integer;
      name : string;
   end;
   
   F_RR = file of RegRec;

(* *)
procedure ShowAllRecs(var fileReg: F_RR);
var i : integer;
var regSought : RegRec;

begin
   for i := 2 downto 0 do
   begin
      seek(fileReg, i); {zero based record}
      read(fileReg, regSought);
      writeln(regSought.name);
   end;
   
end;

(* *)
var
   arr_reg     : array [1..3] of RegRec;
   fileReg     : F_RR;
   i           : integer;
   Error       : integer;
   regSought   : RegRec;
   strVal      : string;

(* *)
begin
   val(strVal, i, Error);
   
   {Create a number of records to write to the file}
   for i := 1 to 3 do
   begin
      str(i, strVal);
      arr_reg[i].number := i;
      arr_reg[i].name := 'fred'+strVal;
   end;
   
   {Create a new output file}
   Assign(fileReg, 'RegFile.dat');
   ReWrite(fileReg);
   
   {Write a number of records to the file}
   for i := 1 to 3 do
   begin
      write(fileReg, arr_reg[i]);
   end;
   
   {Move file pointer back to the beginning of the file}
   Reset(fileReg);
   
   {See all records in file}
   ShowAllRecs(fileReg);

   {Change a record}
   regSought.name := 'Clarence';
   seek(fileReg, 1);
   write(fileReg, regSought);
   
   {See the change}
   ShowAllRecs(fileReg);
   
   close(fileReg);
end.

Ok, i have already done this, in a similar way, the diference was that i didn't know the size of my file, I used this structure:

for i:= to (filesize(arq) - 1) do
begin
   seek(arq,i);
   read(arq,reg);
   if (search = reg.x) then
   begin
      reg.x = newX;
      write(arq,reg);
   end;
end;

Thanks.

good deal.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.