Search code examples
databasegoio

Is it possible to just replace a particular line in a file without rewriting the whole file


I was trying to construct a function which would say given a line number replace that line with another string. Currently, I'm achieving this by reading the whole file into my RAM, modifying the line in RAM and rewriting the whole file back. I was wondering how databases managed to achieve this since this is a rather frequent operation over there.


Solution

  • line implies a text file, and since those generally have varying line lengths, there is no way to replace a line in the file on disk unless the new one has the same length (the operating system does not provide a way to open or close gaps in a file).

    Databases, on the other hand, generally operate on fixed-size entities (per table), so there, the database can replace the content of a 'record' with new data and also keep a list of previously used records that are now deleted and can be recycled when new data is inserted.