《Visual C++ 角色扮演游戏程序设计》-File.h

File.h
自定义了文件的输入输出,把僵硬的api封装起来。
关键字:inline 内联函数:解决频繁调用的小函数大量消耗栈空间(栈内存)的问题

//
// 档案的输入与输出
//
//      Copyright (c) 2000-2001 Chihiro.SAKAMOTO (HyperWorks)
//
#ifndef __FILE_H__
#define __FILE_H__

#include <io.h>
/*
输入输出函数的头文件
*/
#include <stdio.h>
#include <share.h>
/*
共享模式打开文件,安全性比fopen高
*/

//
//  CFile Class
//
class CFile {
  public:
    enum//  枚举
    {
        read,//读
        write,//写
    } ;
    enum    
    {
        begin = SEEK_SET,//文件头
        current = SEEK_CUR,//当前位置
        end = SEEK_END,//文件尾
    } ;

  public:
    CFile(): fp(0) {}
    CFile(const char *file, int mode=read);
    ~CFile();

    bool Open(const char *file, int mode=read);
    bool Close();

    int Read(void *buffer, int length);
    int Write(const void *buffer, int length);
    long Seek(long offset, int from);

#ifdef _MSC_VER
    long GetFileSize() { return _filelength(_fileno(fp)); }
#else
  #ifdef __BORLANDC__//兼容Borland
    long GetFileSize() { return filelength(_fileno(fp)); }
  #endif
#endif

    bool IsOk() const { return fp != 0; }
    bool Error() { return ferror(fp) != 0; }

    bool operator !() { return fp == 0 || ferror(fp) != 0; }//重载!=

  protected:
    FILE *fp;
} ;

// inline成员函数

// 构建式
//
// 判随档案开启的建构
//
inline CFile::CFile(const char *file, int mode)
{
    Open(file, mode);
}

//
// 构建式
//
// 如果还没关闭,就关闭它
//
inline CFile::~CFile()
{
    Close();
}

//
// 开启档案
//
// 读和写的模式
//
inline bool CFile::Open(const char *file, int mode)
{
#ifdef _MSC_VER
    fp = _fsopen(file, mode == read? "rb": "wb", _SH_DENYWR);
#else
    fp = fopen(file, mode == read? "rb": "wb");
#endif
    return fp != 0;
}

//
// Closing
//
inline bool CFile::Close()
{
    if (fp != 0) {
        fclose(fp);
        fp = 0;
    }
    return TRUE;
}

//
// Reading
//
inline int CFile::Read(void *buffer, int length)
{
    return fread(buffer, 1, length, fp);
}

//
// Writing
//
inline int CFile::Write(const void *buffer, int length)
{
    return fwrite(buffer, 1, length, fp);
}

//
// 改变档案的存放位置
//
inline long CFile::Seek(long offset, int from)
{
    return fseek(fp, offset, from);
    //int fseek(FILE *stream, long offset, int fromwhere);函数设置文件指针stream的位置。
}

#endif

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值