此类中会用到一个boost相关的函数,见:http://blog.csdn.net/kanguolaikanguolaik/article/details/9130945
ma_file_op.h:
//
//Descript: file operation class
// Author: guowenyan
// Date: 2013.06.14
//
#pragma once
#include <string>
#include <fstream>
class CMaFileOp
{
public:
CMaFileOp(const std::string &file_name);
~CMaFileOp();
public:
bool open_file();
bool seek_file(long offset, int origin);
bool read_line_file(std::string &str_line, long offset, int origin);
bool read_file(char buf[], int len, long offset, int origin);
bool write_file(char buf[], int len, long offset, int origin);
void close_file();
private:
std::string m_file_name;
std::fstream m_file;
};
ma_file_op.cpp:
//
//Descript: file operation class
// Author: guowenyan
// Date: 2013.06.14
//
#include "ma_file_op.h"
#include "ma_dir_op.h"
#include <iostream>
using namespace std;
CMaFileOp::CMaFileOp(const string &file_name) : m_file_name(file_name)
{
}
CMaFileOp::~CMaFileOp()
{
close_file();
}
bool CMaFileOp::open_file()
{
CMaDirOperation dir_op;
if(!dir_op.is_file_exist(m_file_name))
{
m_file.open(m_file_name.c_str(), ios::out);
m_file.close();
}
m_file.open(m_file_name.c_str(), ios::out|ios::in);
if(!m_file)
{
cout<<"Fail to open file "<<m_file_name.c_str()<<"."<<endl;
return false;
}
return true;
}
bool CMaFileOp::seek_file(long offset, int origin)
{
if(!m_file.is_open())
return false;
m_file.seekg(offset, (ios_base::seekdir)origin);
return true;
}
bool CMaFileOp::read_line_file(std::string &str_line, long offset, int origin)
{
if(!m_file.is_open())
return false;
m_file.seekg(offset, (ios_base::seekdir)origin);
getline(m_file, str_line);
return true;
}
bool CMaFileOp::read_file(char buf[], int len, long offset, int origin)
{
if(!m_file.is_open())
return false;
m_file.seekg(offset, (ios_base::seekdir)origin);
m_file.read(buf, len);
return true;
}
bool CMaFileOp::write_file(char buf[], int len, long offset, int origin)
{
if(!m_file.is_open())
return false;
m_file.seekp(offset, (ios_base::seekdir)origin);
m_file.write(buf, len);
return true;
}
void CMaFileOp::close_file()
{
if(m_file.is_open())
{
m_file.close();
}
}