ofstream和ifstream的详细用法

ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间;

ofstream:文件写操作 内存写入存储设备  

ifstream:文件读操作,存储设备读区到内存中

fstream:读写操作,对打开的文件可进行读写操作 

在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符:
1、插入器(<<)
  向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<'\n';就表示
把字符串"Write Stdout"和换行字符('\n')输出到标准输出流。
2、析取器(>>)
  从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示
从标准输入流中读取一个指定类型(即变量x的类型)的数据。
  在C++中,对文件的操作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式操作文件,就必须加入头文件fstream.h。下面就把此类的文件操作过程一一道来。
bool MyGame::isFileExist(const char *path)
{
    FILE *fp = fopen(path, "r");//r表示只读文件
    bool bRet = false;

    if (fp)
    {
        bRet = true;
        fclose(fp);
    }

    return bRet;
}

void MyGame::saveGameData(bool playing, char *gridData, int maxScore, int level, int currentLevelBeginScore, int score){
    ofstream ofs(m_gameDataPath.c_str());
    if (ofs.is_open())
    {
        ofs<<maxScore<<" "<<level<<" "<<currentLevelBeginScore<<" "<<score<<" "<<playing<<" ";
        if (playing)
        {
            for(int i = 0; i < GameScene::GRID_COUNT_LANDSCAPE * GameScene::GRID_COUNT_PORTRAIT; i++){
                ofs<<gridData[i]<<" ";
            }
        }
        ofs.close();
    }
}
<pre name="code" class="cpp">void MyGame::openGameScene(bool recover){
    bool playing = false;
    char gridData[GameScene::GRID_COUNT_LANDSCAPE * GameScene::GRID_COUNT_PORTRAIT];
    int maxScore = 0;
    int level = 1;
    int currentLevelBeginScore = 0;
    int score = 0;
    if (isFileExist(m_gameDataPath.c_str()))
    {
        ifstream ifs(m_gameDataPath.c_str());
        if (ifs.is_open())
        {
            ifs>>maxScore;
            ifs>>level>>currentLevelBeginScore>>score>>playing;
            if (!playing)
            {
                maxScore= maxScore < score ? score : maxScore;
            }
            if (recover)
            {
                if (playing)
                {
                    for(int i = 0; i < GameScene::GRID_COUNT_LANDSCAPE * GameScene::GRID_COUNT_PORTRAIT; i++){
                        ifs>>gridData[i];
                    }
                }
            }else{
                level = 1;
                currentLevelBeginScore=0;
                score=0;
                playing = false;
            }
            ifs.close();
	}
     }
}
 
 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值