在C++中连接两个大文件

2024-01-26

我有两个 std::ofstream 文本文件,每个文件有一百多兆,我想将它们连接起来。使用 fstream 存储数据来创建单个文件通常会因大小太大而导致内存不足错误。

有没有比 O(n) 更快的方法来合并它们?

文件 1 (160MB):

0 1 3 5
7 9 11 13
...
...
9187653 9187655 9187657 9187659 

文件 2 (120MB):

a b c d e f g h i j
a b c d e f g h j i
a b c d e f g i h j
a b c d e f g i j h
...
...
j i h g f e d c b a

合并(380MB):

0 1 3 5
7 9 11 13
...
...
9187653 9187655 9187657 9187659 
a b c d e f g h i j
a b c d e f g h j i
a b c d e f g i h j
a b c d e f g i j h
...
...
j i h g f e d c b a

文件生成:

std::ofstream a_file ( "file1.txt" );
std::ofstream b_file ( "file2.txt" );

    while(//whatever){
          a_file << num << endl;
    }

    while(//whatever){
          b_file << character << endl;
    }

    // merge them here, doesn't matter if output is one of them or a new file
    a_file.close();
    b_file.close();

假设您不想进行任何处理,只想连接两个文件以形成第三个文件,则可以通过流式传输文件的缓冲区来非常简单地完成此操作:

std::ifstream if_a("a.txt", std::ios_base::binary);
std::ifstream if_b("b.txt", std::ios_base::binary);
std::ofstream of_c("c.txt", std::ios_base::binary);

of_c << if_a.rdbuf() << if_b.rdbuf();

我过去曾尝试过处理最大 100Mb 的文件,但没有出现任何问题。您可以有效地让 C++ 和库处理所需的任何缓冲。这也意味着如果您的文件被删除,您无需担心文件位置really big.

另一种选择是如果您只想复制b.txt到结束时a.txt,在这种情况下您需要打开a.txt使用追加标志,并查找到末尾:

std::ofstream of_a("a.txt", std::ios_base::binary | std::ios_base::app);
std::ifstream if_b("b.txt", std::ios_base::binary);

of_a.seekp(0, std::ios_base::end);
of_a << if_b.rdbuf();

这些方法的工作原理是通过传递std::streambuf输入流的operator<<输出流的,其覆盖之一需要streambuf范围 (运算符)。正如该链接中提到的,在没有错误的情况下,streambuf以未格式化的方式插入到输出流中,直到文件末尾。 http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在C++中连接两个大文件 的相关文章

随机推荐