文本文件合并(C++实现)
生活随笔
收集整理的這篇文章主要介紹了
文本文件合并(C++实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
直接附上代碼吧
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
void write_into_file(){
cout<<"請輸入合成后生成的文件名:"<<endl;
string Des_FileName;
cin>>Des_FileName;
cout<<endl;
cout<<"請輸入想要合并原始文件個數:"<<endl;
int cnt;
cin>>cnt;
cout<<endl;
string Source_Array_FileName[cnt];//保存將要合并的各文件
for(int i=0;i!=cnt;++i){
cout<<"請輸入第"<<i+1<<"個原始文件:"<<endl;
cin>>Source_Array_FileName[i];
cout<<endl;
}
cout<<"請稍后,馬上開始合并!"<<endl<<endl;
ofstream outfile(Des_FileName,ios::out);//定義輸出文件流對象,并賦初值,指定模式
ifstream infile;//定義一個輸入文件流對象
char c;//用來暫存從文件獨處的一個字符
for(string Temp_FileName : Source_Array_FileName){
infile.open(Temp_FileName,ios::in);
if(!infile){
cerr<<"打開文件 "<<Temp_FileName<<" 失敗"<<endl;
}
while(infile.get(c)){
outfile<<c;
}
infile<<endl;
infile.close();
cout<<Temp_FileName<<"已經合并到目標文件"<<endl;
}
outfile.close();
cout<<"所有文件合并已完成"<<endl;
}
int main(){
write_into_file();
system("pause");
return 0;
}
總的來說,思路特別簡單,打開一個文件,就將此文件的內容存入到目標文件中,然后執行下一個文件操作,不過吧,還是有需要注意的
在將一個源文件的內容已經轉存入目標文件后,在打開另外一個源文件之前,必須先將當前的輸入文件流關聯的源文件關閉,即用infile.close(),不然就不能打開下一個文件
再附上一個測試結果吧
總結
以上是生活随笔為你收集整理的文本文件合并(C++实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 衬衫款式图(衬衫配什么裤子)
- 下一篇: 互信息