I copy file on linux with sendfile. Below is the example how I use it
struct stat statBuf;
fstat(fdFrom, &statBuf);
sendfile(fd, fdFrom, 0, statBuf.st_size);
close(fd);
close(fdFrom);
Documentation to sendfile says that it may not write all bytes at once. Is the way how I use it safe? Or I should implement loop in which I check result of sendfile until will be 0?
Descriptors are from local files.
Should be target file truncated to zero before copying bytes from source file?
Yes, you should loop and sum up the bytes transfered until you've sent all of them. It could look something like this:
If you want the target file to be an exact copy, then yes,
openit with theO_TRUNCflag set - or callftruncate(fd, statBuf.st_size);after the copying has been done just in case the previous content was larger than what you just copied.