【发布时间】: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 的解释很有道理。