【问题标题】:Is it possible to use sendfile() to copy directories是否可以使用 sendfile() 复制目录
【发布时间】:2014-06-05 04:16:32
【问题描述】:

我正在尝试使用sendfile() 来实现复制程序。

但是当我尝试复制目录时它失败了。目录不是Linux中的一种特殊文件类型吗?

这是我现在使用的代码。它是从 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;
}

追加

我得到的返回值是-1。我得到了一个文件,而不是目录,它有to 路径。

我使用的是 Ubuntu 12.04,64 位。

uname -r 的输出是3.11.0-20-generic

【问题讨论】:

  • 哪里失败了?您不检查任何返回值!你得到什么错误?它是什么内核版本?
  • 可能您的一个公开呼叫失败或两者兼而有之。还要检查 errno 变量。 linux.die.net/man/2/sendfile
  • @Malkocoglu 已检查,未设置 errno。我觉得 Tripleee 的解释很有道理。

标签: c linux sendfile


【解决方案1】:

您不能像这样传输目录。虽然从技术上讲,目录确实是某些 Unices 上的一种文件,但它的内容不能移植到另一个文件系统,甚至不能移植到同一文件系统中的另一个目录。由于这个和其他原因,系统不允许您将目录视为另一个文件。

【讨论】:

  • 知道了。但这没有记录在sendfile() 手册页中。所以我想,我会用mkdir() 来复制目录。
【解决方案2】:

【讨论】:

  • 是的...我已经完成了一些谷歌的工作,并且看看这个。这不是我想要的。我想使用sendfile()
猜你喜欢
  • 1970-01-01
  • 2011-04-11
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2014-11-07
相关资源
最近更新 更多