合并大文件

0 c++

我正在尝试在C++中加入两个大文件(如UNIX cat命令:cat file1 file2> final).

我不知道怎么做,因为我尝试的每个方法都很慢(例如,将第二个文件逐行复制到第一个文件中)

¿这样做的最佳方法是什么?

很抱歉这么简短,我的英语不太好

Ara*_*raK 6

在标准流中使用二进制模式来完成工作,不要将其作为格式化数据处理.


如果您想要以块为单位传输数据,这是一个演示:

#include <fstream>
#include <vector>

std::size_t fileSize(std::ifstream& file)
{
    std::size_t size;

    file.seekg(0, std::ios::end);
    size = file.tellg();
    file.seekg(0, std::ios::beg);

    return size;
}

int main()
{
    // 1MB! choose a conveinent buffer size.
    const std::size_t blockSize = 1024 * 1024;

    std::vector<char> data(blockSize);
    std::ifstream first("first.txt", std::ios::binary),
                second("second.txt", std::ios::binary);
    std::ofstream result("result.txt", std::ios::binary);
    std::size_t firstSize  = fileSize(first);
    std::size_t secondSize = fileSize(second);

    for(std::size_t block = 0; block < firstSize/blockSize; block++)
    {
        first.read(&data[0], blockSize);
        result.write(&data[0], blockSize);
    }

    std::size_t firstFilerestOfData = firstSize%blockSize;

    if(firstFilerestOfData != 0)
    {
        first.read(&data[0], firstFilerestOfData);
        result.write(&data[0], firstFilerestOfData);
    }

    for(std::size_t block = 0; block < secondSize/blockSize; block++)
    {
        second.read(&data[0], blockSize);
        result.write(&data[0], blockSize);
    }

    std::size_t secondFilerestOfData = secondSize%blockSize;

    if(secondFilerestOfData != 0)
    {
        second.read(&data[0], secondFilerestOfData);
        result.write(&data[0], secondFilerestOfData);
    }

    first.close();
    second.close();
    result.close();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Pav*_*aev 6

如果你正在使用std::fstream,那就不要.它主要用于格式化的输入/输出,并且它的char级操作比你期望的慢.相反,std::filebuf直接使用.这是对其他答案中的建议的补充,特别是使用较大的缓冲区大小.