Skip to content
Advertisement

Adding content to middle of file..without reading it till the end

I have read various questions/answers here on unix.stackexchange on how to add or remove lines to/from a file without needing to create a temporary file.

https://unix.stackexchange.com/questions/11067/is-there-a-way-to-modify-a-file-in-place?lq=1

It appears all these answers need one to atleast read till end of the file, which can be time consuming if input is a large file. Is there a way around this? I would expect a file system to be implemented like a linked list…so there should be a way to reach the required “lines” and then just add stuff (node in linked lists). How do I go about doing this?

Am I correct in thinking so? Or Am I missing anything?

Ps: I need this to be done in ‘C’ and cannot use any shell commands.

Advertisement

Answer

You can modify a file in place, for example using dd.

$ echo Hello world, how are you today? > helloworld.txt
$ cat helloworld.txt
Hello world, how are you today?
$ echo -n Earth | dd of=helloworld.txt conv=notrunc bs=1 seek=6
$ cat helloworld.txt
Hello Earth, how are you today?

The problem is that if your change also changes the length, it will not quite work correctly:

$ echo -n Joe | dd of=helloworld.txt conv=notrunc bs=1 seek=6
Hello Joeth, how are you today?
$ echo -n Santa Claus | dd of=helloworld.txt conv=notrunc bs=1 seek=6
Hello Santa Clausare you today?

When you change the length, you have to re-write the file, if not completely then starting at the point of change you make.

In C this is the same as with dd. You open the file, you seek, and you write.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement