Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepending Data to a File

There's no way in any operating system I'm aware of for a program to prepend data to a file efficiently. And yet, this doesn't seem difficult -- the file system can add another extent to a file descriptor if needed.

So the question is, why don't operating systems implement this (rather trivial) operation?

like image 834
user541686 Avatar asked Apr 06 '11 00:04

user541686


People also ask

How do I append data to a file in Linux?

You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.

How do you prepend text in Linux?

1s;^;to be prepended; substitutes the beginning of the first line by the given replacement string, using ; as a command delimiter.


1 Answers

I don't think it's as easy as you suggest. It's true that the file-system could allocate a new block, store the prepended data in it, change the file pointer to point to that block and then chain the rest of the file from that block. Just like adding a node to the front of a linked list, right?

But what happens when (as is probably the case) the prepended data doesn't fill the assigned block. I don't imagine that many filesystems would have a machanism for chaining partial blocks, but even if they do it would result in huge inefficiencies. You'd end up with a file consisting of mostly empty blocks, and you have to have to read and write the entire file to defragment it. Might as well just do the read-and-write operation up front when you're prepending in the first place.

like image 107
Andrew Cooper Avatar answered Jan 03 '23 11:01

Andrew Cooper