[LC++]Copying files and deleting directories
Paul Gearon
gearon at ieee.org
Fri Sep 10 10:08:02 UTC 2004
On 10/09/2004, at 7:33 AM, Krishna Monian wrote:
> Hi,
> So what is the best way to implement my own version of
> copy?
>
> Currently, I open the file, read a certain number of
> bytes into a buffer and then write it into the file
> until I am done. This is a very lame way I would say.
No, that's just fine. Just make sure that the size of your buffer
isn't tiny, else you'll call read and write too often. IIRC cp uses
this method for small files. Whatever you do, don't use fread and
fwrite.
For larger files cp uses mmap. To do this, you just map the source
file, then you create, expand, and map the destination file, and
finally you do a memcpy from one map to the other. It's actually quite
easy to do. This method has more overhead to set up, but skips a
memory copy of the data (which is why it's faster for large files).
> I might have several files to copy at a time (1000s).
> From your discussion it seems that the system function
> will be relatively slow for this purpose.
If you have lots of files, then set up time is important. If the files
are small, then using read/write would probably offer the best option
here.
> Is there some better way to go about doing this? It
> doesn't have to faster than cp. Anything faster than
> my current method is acceptable.
Just use a read/write loop on a decent sized buffer. If you discover
that it's too slow for what you need, then you can look at optimising
with mmap. Don't fall into the pre-optimising trap!
Regards,
Paul Gearon
Software Engineer
Tucana Technologies
http://www.tucanatech.com
Catapultam habeo. Nisi pecuniam omnem mihi dabis, ad caput tuum saxum
immane mittam.
(Translation from latin: "I have a catapult. Give me all the money,
or I will fling an enormous rock at your head.")
More information about the tuxCPProgramming
mailing list