[PATCH] adding two new options to 'cp'

Rick C. Petty rick-freebsd at kiwi-computer.com
Tue Aug 1 17:11:52 UTC 2006


On Tue, Aug 01, 2006 at 05:26:11PM +1000, Peter Jeremy wrote:
> On Mon, 2006-Jul-31 22:42:49 +0200, Ivan Voras wrote:
> >I agree with this, and while you're in there, can you add -s to copy 
> >sparse files (via the usual "if the buffer is all nulls, seek beyond eof 
> >instead of writing" trick)?
> 
> Note that it isn's possible to accurately distinguish between a block
> of NULs and a hole in the file through the filesystem.  The only way
> to accurately copy a sparse file is with dump/restore.

Sure it is-- in a number of ways.  The most useful way is to do something
of the sort:

  int sd, dd;	// assume these are set to source & dest descriptors
  unsigned char* zeros;
  unsigned char* buffer;
  struct stat st;
  size_t bytes, offset;

  fstat(sd, &st);
  zeros = malloc(st.st_blksize);
  bzero(zeros, st.st_blksize);

  for (offset = 0; offset < st.st_size; offset += bytes)
  {
    bytes = st.st_blksize;
    if (offset + bytes > st.st_size)
      bytes = st.st_size - offset;
    read(sd, buffer, bytes);
    if (0 == memcmp(buffer, zeros, bytes))
      lseek(dd, bytes, SEEK_CUR);
    else
      write(sd, buffer, bytes);
  }

Obviously, I didn't add the error checking/handling, but AFAIK this is
essentially what the -S option to gnu's tar does.  In this example, you
may not mimic the allocated blocks of a sparse file, but you would
optimize the copy to use as few filesystem blocks as possible.

-- Rick C. Petty


More information about the freebsd-hackers mailing list