最近处理数据,经常需要读一行数据,处理,写入文件,采用fprintf函数效率很低,好的做法就是先把数据写入缓冲区,然后缓冲区满后再写入文件,这样减少IO操作。下面吧这个功能封装,构造函数需要写入输出文件路径已经缓冲区大小,然后writeToFile函数实现将字符串写入文件,最后用close来关键文件以及清空缓冲区
#ifndef FILEBUFF_H #define FILEBUFF_H #include <fstream> #include <cstring> #include <string> using namespace std;
class FileBuff { public: FileBuff(const string& out_file, int buff_size):/ m_flag(0),m_BUFFSIZE(buff_size) { m_buff = new char[m_BUFFSIZE]; m_of.open(out_file.c_str(), ios::out); if(!m_of) { cerr<<"Failed to open file"<<endl; exit(-1); }
} int WriteToFile(const string &str) { int len = str.size(); if(len >= m_BUFFSIZE) { m_of<<str; return 1; } int remain = m_BUFFSIZE - m_flag - 1;//one for /0 if(len > remain) { m_of<<m_buff; m_flag = 0; } strcpy( m_buff + m_flag,str.c_str()); m_flag += len; m_buff[m_flag] = '/0';
} int close() { m_of<<m_buff; m_of.close(); delete[] m_buff; } ~FileBuff() { } private: int m_flag;//the first pos can be used char *m_buff; fstream m_of; int m_BUFFSIZE; }; #endif