Fstream fails to create new file

前端 未结 6 1043
梦如初夏
梦如初夏 2021-01-12 22:57

I\'m using a FileManager for a project so that reading and writing is less of a hassle for me. Or would be, if I didn\'t spend all this time debugging it. So, this comfort-c

6条回答
  •  囚心锁ツ
    2021-01-12 23:26

    Best method:

    void FileManager::open(std::string const& filename)
    {
        using std::ios_base;
        if( stream_.is_open() )
            stream_.close();
    
        stream_.open( filename.c_str() ); // ...try existing file
        if( !stream_.is_open() ) // ...else, create new file...
            stream_.open(filename.c_str(), ios_base::in | ios_base::out | ios_base::trunc);
    }
    

    So the code tests for an existing file and, if not, creates it.

提交回复
热议问题