在C/C++中将数据从一个文件复制到另一个文件的最快方法?

sta*_*son 3 c c++ file-io fwrite fread

在我的代码中,我有一种情况需要将数据从一个文件复制到另一个文件.我想出的解决方案如下:

const int BUF_SIZE = 1024;
char buf[BUF_SIZE];

int left_to_copy = toCopy;
while(left_to_copy > BUF_SIZE)
{
    fread(buf, BUF_SIZE, 1, fin);
    fwrite(buf, BUF_SIZE, 1, fout);
    left_to_copy -= BUF_SIZE;
}

fread(buf, left_to_copy, 1, fin);
fwrite(buf, left_to_copy, 1, fout);
Run Code Online (Sandbox Code Playgroud)

我的主要想法是可能有类似memcpy的东西,但是对于文件中的数据.我只给它两个文件流和总字节数.我搜索了一下,但我找不到任何这样的东西.

但是如果没有这样的东西,我应该使用什么缓冲区大小来实现最快的传输?更大意味着更少的系统调用,但我认为它可能会破坏系统上的其他缓冲或缓存.我应该动态分配缓冲区,以便只进行一对读/写调用吗?在这种特定情况下,典型的传输大小是从几KB到十几MB.

编辑:对于操作系统特定信息,我们使用的是Linux.

EDIT2:

我尝试使用sendfile,但它没有用.它似乎写了适量的数据,但它是垃圾.

我用上面这样的东西替换了我的例子:

fflush(fin);
fflush(fout);
off_t offset = ftello64(fin);
sendfile(fileno(fout), fileno(fin), &offset, toCopy);
fseeko64(fin, offset, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)

我添加了flush,offest,并且一次寻找一个,因为它似乎没有工作.

kay*_*kay 11

你需要告诉我们你想要的操作系统.适当的调用(或者说最合适的调用)将是非常系统特定的.

在Linux/*BSD/Mac中,您将使用sendfile(2)它来处理内核空间中的复制.

概要

 #include <sys/sendfile.h>
 ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);
Run Code Online (Sandbox Code Playgroud)

描述

sendfile() copies data between one file descriptor and another.  Because this
copying is done within the kernel, sendfile() is more efficient than the
combination of read(2) and write(2), which would require transferring data to
and from user space.

in_fd should be a file descriptor opened for reading and out_fd should be a
descriptor opened for writing.
Run Code Online (Sandbox Code Playgroud)

进一步阅读: