Question

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.

Was it helpful?

Solution

You cannot transmit a directory like this. While technically it is true that a directory is a kind of file on some Unices, its contents are not portable to another file system, or even another directory in the same file system. For this and other reasons, the system won't allow you to treat a directory as just another file.

OTHER TIPS

Here is the implementation of the copy command in linux. Please follow this.

http://cboard.cprogramming.com/c-programming/143382-implementation-linux-cp-copy-command-c-language.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top