I'm trying to use sendfile()
to implement a copy program.
However it failed when I was trying to copy directories. Isn't directory a special file type in Linux?
Here is the code I'm using now. It's copied from another answer from StackOverflow.
int copy_file(const char *to, const char *from) {
int read_fd; int write_fd;
struct stat stat_buf;
off_t offset = 0;
/* Open the input file. */
read_fd = open(from, O_RDONLY);
/* Stat the input file to obtain its size. */
fstat (read_fd, &stat_buf);
/* Open the output file for writing, with the same permissions as the source file. */
write_fd = open(to, O_WRONLY | O_CREAT, stat_buf.st_mode);
/* Blast the bytes from one file to the other. */
int err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size);
/* Close up. */
close (read_fd);
close (write_fd);
return err;
}
Appending
The return value I got is -1. And I got a file, not directory, that have to
path.
I'm using Ubuntu 12.04, 64bit.
The output of uname -r
is 3.11.0-20-generic
.