如果缓冲区大小小于文件大小,如何合并两个文件
How to merge two files if the buffer size is smaller than the size of the file?
如果缓冲区大小小于文件大小,如何合并两个文件?例如,我有两个带有排序整数的文件
1.txt和2.txt
2 1
5 7
6 8
7 9
我必须将它们合并到一个排序的文件中,但从每个文件中读取的数字不能超过两个(这就是任务)。我的记忆中不能同时有4个以上的数字。
这是我的代码
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
const int bufferSize = 2;
bool readSortFile(ifstream &file, vector<int> &data) {
int tmp;
for (int i = 0; (i < bufferSize && file >> tmp); i++)
data.push_back(tmp);
return file.good();
}
int main() {
ifstream file1("1.txt");
ifstream file2("2.txt");
ofstream out;
vector<int> data1, data2;
bool fileGood1, fileGood2;
fileGood1 = true;
fileGood2 = true;
while(fileGood1 || fileGood2) {
if(data1.size() == 0)
fileGood1 = readSortFile(file1, data1);
if (data2.size() == 0)
fileGood2 = readSortFile(file2, data2);
out.open("temp", ios::app);
merge(data1.begin(),
data1.end(),
data2.begin(),
data2.end(),
ostream_iterator<int>(out, "n"));
data1.clear();
data2.clear();
out.close();
}
rename("temp", "result.txt");
file1.close();
file2.close();
return 0;
}
输出为1 2 5 7 6 7 8 9
如注释中所述,您只需要每个文件中的一个数字就可以实现合并,但您可能需要编写自己的合并逻辑,而不是使用std::merge。例如伪代码,您需要添加eof检查(如果1.txt结束,则复制2.txt的其余部分,反之亦然)。
num1 = get number from "1.txt"
num2 = get number from "2.txt"
loop(...){
if(num1 <= num2){
write num1
num1 = get number from "1.txt"
} else {
write num2
num2 = get number from "2.txt"
}
}
相关文章:
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 合并文本文件不同行中的重复项
- 将两个 cpp 文件合并为一个 cpp 文件
- 将所有 *.txt 文件合并到一个文本文件中,其名称由用户使用 C++ 提供
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 是否可以将前向声明和常规声明合并到一个文件中,然后像分开一样使用它?
- 在 C++ 优化中合并大型二进制文件
- 如何将SQLite c文件(合并)与cpp应用程序链接?
- CMake 项目结构:如何正确地将库合并在一起并将它们包含在多个可执行文件中
- 如何使用可执行文件将我的C++代码合并到我的 Xcode 项目中
- 我的合并sort.h文件中的代码出了什么问题
- 将多个 stl 文件合并为一个
- 合并 c++ obj 文件以进行 C 链接
- 如何在windows上构建Botan合并文件Botan_all.cpp和.h
- C++合并文件时出现问题
- 按最顶端合并文件夹列表
- 为什么多个文件的编译速度比合并文件快得多
- 编写一个C++程序,可以在Linux中从命令行合并文件
- 如何使用Botan合并文件和VS2008
- 在c++(windows)中连接/附加/合并文件,而不进行复制