Thomas Jomphe Thomas Jomphe - 4 months ago 48
Pascal Question

Insert record in the middle of a binary file in Delphi

I'm creating a program in Delphi and I need to insert a record in a binary file, but between 2 existing records. Can anyone help me ?

Answer

If you really want to insert, then you'll have to create a new file with a different name, copy the old file content, up to the insert spot, to the new file, then write the new record to the new file and finally copy the rest of the old file to the new file. Then delete the old file and rename the new file to the name of the old one.

Original file:

[A][B][C][D][E][F][G][H]
            ^
            insertion point 

First copy content before insertion point:

[A][B][C][D]

write new record:

[A][B][C][D][Z]

and then copy the rest:

[A][B][C][D][Z][E][F][G][H]

If you only want to replace a record, then take a look at random access I/O, either using old Pascal Seek and BlockRead/BlockWrite, or streams, using TStream.Seek and TStream.Write. The latter is the more contemporary way of doing things.

Update

As suggested in the comments, you can also do the following (using the same routines as described above):

Open the file for reading and writing, increase the size of the file by the size of the record to insert, move the content "above" the insertion point out of the way to the higher file "address" and then write the record to the insertion point.

Before:

[A][B][C][D][E][F][G][H]
            ^
            insertion point 

then move E onward up:

[A][B][C][D][E][E][F][G][H]
            ^  <---------->

and finally write the new record:

[A][B][C][D][Z][E][F][G][H]
            ^  <---------->

If you want to copy content in chunks (say, 4k chunks), then don't forget to do it backward (from high file pointer to low), so you don't overwrite content you did not read yet. Or you use a double buffer. Or ...


You can make this as complicated as you wish. I personally would probably copy to a new file, delete the old and rename the new file and be done with it.