文本文件合并(C++实现)
时间: 2023-07-11 19:42:15 浏览: 182
可以使用C++中的fstream库来实现文本文件的合并。具体步骤如下:
1. 打开需要合并的文件,同时创建一个新文件用于存放合并后的内容。
```c++
#include <fstream>
using namespace std;
int main()
{
// 打开需要合并的文件
ifstream file1("file1.txt");
ifstream file2("file2.txt");
// 创建新文件
ofstream outfile("outfile.txt");
// ...
}
```
2. 逐行读取需要合并的文件,并将内容写入新文件中。
```c++
string line;
// 从file1中读取每一行,并写入outfile中
while (getline(file1, line))
{
outfile << line << endl;
}
// 从file2中读取每一行,并写入outfile中
while (getline(file2, line))
{
outfile << line << endl;
}
```
3. 关闭所有文件。
```c++
file1.close();
file2.close();
outfile.close();
```
完整代码:
```c++
#include <fstream>
using namespace std;
int main()
{
// 打开需要合并的文件
ifstream file1("file1.txt");
ifstream file2("file2.txt");
// 创建新文件
ofstream outfile("outfile.txt");
string line;
// 从file1中读取每一行,并写入outfile中
while (getline(file1, line))
{
outfile << line << endl;
}
// 从file2中读取每一行,并写入outfile中
while (getline(file2, line))
{
outfile << line << endl;
}
// 关闭所有文件
file1.close();
file2.close();
outfile.close();
return 0;
}
```