ofstream和ifstream的详细用法

来源:互联网 发布:ntp服务器地址 端口 编辑:程序博客网 时间:2024/06/05 22:45

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 0
原创粉丝点击