Question

One of the side uses of ftruncate() is that we can resize a file by just sticking zeros onto the end of the file assuming that you request a new file size larger than the original. This seems like a low cost solution to resizing a file since it modifies the file descriptor, etc. This is a great solution when we want the newly created region to exist at the end of the file (similar to how realloc() gives you the new space after your original content).

But what about the beginning! What if I want to resize the file but get my new space at the beginning of the file? I can't really believe that I have to simply copy all of the data into a later portion of the file (or do I?). It would be a terribly time consuming operation! Is there a better way?

Was it helpful?

Solution

I don't think so, especially not in a an OS agnostic way. You would be depending on the OS to allocate a disk block and prepending it to the list of blocks the file uses. Blocks are of a fixed size, so even if there was a way your data would have to match the block size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top