STL之文件读写类fstream

此类中会用到一个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();
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值