Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting a record in binary mode without creating a temp file (C file I/O)

All the codes so far I referred uses temp file to delete a record from file.
Ex:

fp=fopen(“foo.db”,”rb”);
ft=fopen(“temp.db”,”wb”);
//check both files opened or created successfully. Terminate program accordingly 
while(fread(&foo,sizeof(Foo),1,fp))
{
    if(record matched)
    {
        //skip this record
    }
    else
    {
        //write a record in temp file
        fwrite(&foo,sizeof(Foo),1,ft);
    }
}

fclose(fp);
fclose(ft);
remove(“foo.db”); //remove original file
rename(“temp.db”,”foo.db”); //rename temp.db to foo.db

is this the only way we can implement deleting record ?
i can think of overlaping next record to previous record.
but how do i terminate last record and mark end of file in binary mode ?
i also saw this post but no clues

like image 502
Sagar Avatar asked Feb 02 '26 22:02

Sagar


1 Answers

It could be operating system specific. In general, files are a sequence of bytes, and you cannot remove a segment of bytes in the middle. You should consider using a library providing indexed files like GDBM, or a database like Sqlite (or a real DBMS like PostGreSQL, MongoDb, MariaDb etc....)

Both GDBM and Sqlite (and often real DBMS) are built above existing file systems, but provide some high-level abstraction.

In other words, you should not use plain binary files in your case, if you want to avoid copying them. As commented by user3121023 you might manage links in your fixed length records and manage a free list, etc... Libraries like GDBM and Sqlite are also able to do something similar.

I know no file system or operating system which is able to remove a segment of bytes in the middle, and there is no POSIX API for this.

like image 74
Basile Starynkevitch Avatar answered Feb 04 '26 16:02

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!