user3645376
user3645376

Reputation: 1

Insert text using Unix syscalls

Unix write system call replaces (overwrites) characters. Is there a way of inserting characters into a unix file. We want to achieve this without making a copy of the file.

Can mmap come to rescue in this situation?

For example, contents of file A before modification:

abcdef
1234567

After modification, contents of file A:

abcdef
:/"}{>
1234567

Upvotes: 0

Views: 138

Answers (2)

ConcernedOfTunbridgeWells
ConcernedOfTunbridgeWells

Reputation: 66662

The short answer is 'No' - the system calls in section 2 of the manual do not support this. On a flat unix file you would have to re-write everything in the file after the data you inserted. mmap would not get around this except you would do it by writing to the mmap()ed memory buffer and letting the O/S take care of the I/O.

If you need to do this efficiently you would need some some sort of chunk structure. A linked list is a simple example of such a structure. If you need random access you would have to overlay a tree structure over it. This is roughly how ISAM type file structures work.

Faking this capability within the O/S would require you to implement something similar in the file system metadata. This escalates your problem into custom file systems and frigging with the kernel, which would be a lot of effort and would make your system incompatible with every one else.

Upvotes: 0

Andy Lester
Andy Lester

Reputation: 93735

No, the idea of "inserting" data is a facade put up by text editors.

If you have a text file and you want to "insert" data into the file, you must read the data, modify it, and write it back out to a new file.

Upvotes: 4

Related Questions