File IO – Alternative to ‘dd’ Without Truncating File

ddfilesio-redirection

Does anyone know an alternative for 'dd', which won't truncate the file, without using: conv=notrunc. Adding conv=notrunc isn't supported via busybox/toybox due to limited amount of space.

For instance, I'd like the equivalent of

dd bs=4 count=3 skip=2 seek=3 if=file.in of=file.out conv=notrunc

But that would work where dd doesn't support conv=notrunc.

Best Answer

Use the standard <> sh redirection operator which opens the file in read+write mode without truncation.

cat < file.in 1<> file.out

To copy the content of file.in at the start of file.out.

If you need to seek in the input or output file, and assuming your dd still supports these directives:

dd bs=4 count=3 skip=2 seek=3 < file.in 1<> file.out

If you don't have dd at all, you can try head -c, assuming your version takes care of leaving the pointer in the file at the right place upon exit (which IIRC older versions of busybox were not doing).

For instance, the equivalent of the above would be:

{
  head -c 8 > /dev/null        # seek input fd to offset 8
  head -c 12 <&1 > /dev/null   # seek output fd to offset 12
  head -c 12                   # copy 12 bytes
} < file.in 1<> file.out