C++中文本文件读取优化使用缓冲

180it 2020-10-13 AM 1631℃ 0条
  1. C++文本文件读写程序(基本方式)
//C++ code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class file{
public:
    //按行读数据,不分行写入另外一个文件
    bool fromShortToLong(string s_path,string d_path){
        string buffer;
        fstream infile(s_path);
        fstream outfile(d_path);
        if(!infile){
            cout << "Unable to open infile";
            exit(1); // terminate with error
        }
        if(!outfile){
            cout << "Unable to open outfile";
            exit(1); // terminate with error
        }do{
            outfile<<buffer;
        }while (getline(infile,buffer));
        cout<<"读写完成。"<<endl;
        system("pause");
        outfile.close();
        infile.close();
    }
};
void main(){
    file test;
    test.fromShortToLong("D://test_read.txt","D://test_write.txt");
}


  1. 使用缓冲的读写程序
bool fromShortToLong(string s_path,string d_path)
{
    string buffer;
    ifstream infile(s_path.c_str());
    ofstream outfile(d_path.c_str());
    if(!infile)
    {
        cout << "Unable to open infile";
        exit(1); // terminate with error
    }
    if(!outfile)
    {
        cout << "Unable to open outfile";
        exit(1); // terminate with error
    }
    buffer.assign(istreambuf_iterator<char>(infile),istreambuf_iterator<char>());
    stringstream strStr;
    strStr.str(buffer);
    string linestr;
    do
    {
        outfile<<linestr;
    }
    while (getline(strStr,linestr));
    cout<<"读写完成。"<<endl;
    return true;
}


后者比前者的读写速度要快很多倍。主要原因就是后者的文件IO次数远远少于前者。

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C++中文本文件读取优化使用缓冲