1

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.

Ply_py
  • 105
  • 1
  • 1
  • 5
  • It failed where ? You do not check any return value ! What is the error you get ? What kernel version is it ? – Malkocoglu Apr 21 '14 at 05:59
  • Maybe one of your open calls failed or both. Also check errno variable. http://linux.die.net/man/2/sendfile – Malkocoglu Apr 21 '14 at 09:02
  • @Malkocoglu Already checked, errno is not set. I think tripleee's explanation makes sense enough. – Ply_py Apr 21 '14 at 09:09

2 Answers2

0

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

Chaithra
  • 1,130
  • 3
  • 14
  • 22
  • Yah... I've already done some google works, and had this looked. It's not what I want. I want to use `sendfile()`. – Ply_py Apr 21 '14 at 06:16
0

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    Got it. But this is not documented in the `sendfile()` man page. So I guess, I'll just use `mkdir()` to copy directories. – Ply_py Apr 21 '14 at 07:25