#include <iostream>
#include <limits>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
void exitWhenInvalidScreen(int input) {
if (input <= 0 || input>1000) {
std::cout << "invalid screen size" << std::endl;
exit(0);
}
}
class Screen {
private:
//----補(bǔ)充多個數(shù)據(jù)域成員
unsigned int _width;
unsigned int _height;
// 在Screen類中獲取/釋放圖形窗口資源锋华,是一種RAII方法
// 關(guān)于RAII庇麦,可以參見異常處理單元的材料
Screen(unsigned int width, unsigned int height) {
// 如果啟用了圖形庫樱蛤,則將初始化圖形模式的函數(shù)置于此處
// initgraph(width_, height_);
_width = width;
_height = height;
};
Screen(){
}
~Screen () {
// 如果啟用了圖形庫旺矾,則將關(guān)閉圖形模式的函數(shù)置于此處
// closegraph();
delete instance;
}
public:
static Screen* instance;
//----補(bǔ)充 getWidth() 與 getHeight() 函數(shù)援岩,
static Screen* getInstance(unsigned int width = 640, unsigned int height = 480) {
// 單例模式
//----補(bǔ)充函數(shù)體
if (instance == 0) {
instance = new Screen(width, height);
}
return instance;
}
unsigned int getWidth(){
return _width;
}
unsigned int getHeight(){
return _height;
}
};
Screen* Screen::instance = 0;
//----補(bǔ)充Screen類的特殊數(shù)據(jù)成員初始化語句
int main() {
int width, height;
Screen* screen = 0;
string filename="screen.txt";
fstream fs;
fs.open(filename,ios::out|ios::in);
if(fs.fail()){
cout<<"open failed!"<<endl;
fs.open(filename,ios::out);
fs.close();
fs.open(filename,ios::out|ios::in);
}
fs>>width>>height;
// cout<<width<<" "<<height<<endl;
if(fs.fail()){
cout<<"reading failed!"<<endl;
cin>>width>>height;
}
fs.clear();
screen = Screen::getInstance(width, height);
screen = Screen::getInstance();
fs.seekp(ios::beg);
fs <<screen->getWidth() << " " <<screen->getHeight();
fs.clear();
fs.seekg(ios::beg);
int getwidth,getheight;
fs>>getwidth>>getheight;
cout<<getwidth<<" "<<getheight<<endl;
fs.close();
// GCC及VC編譯器在調(diào)試模式下會暫停贮折,便于查看運行結(jié)果
#if ( defined(__DEBUG__) || defined(_DEBUG) )
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();
#endif
return 0;
}
說明
假定文件流對象為 fstream fs;
讀寫模式打開文件時遍坟,需要使用 ios::in | ios::out 作為流對象fs的 open 函數(shù)的參數(shù)
判斷文件操作(打開拳亿、讀寫)是否成功,使用 fs.fail() 判斷愿伴。如果成功肺魁, fail() 返回 false,否則返回 true
if (fs.fail()) {
輸出提示信息
用寫模式打開文件
關(guān)閉文件
再次用讀寫模式打開文件
}
打開文件后隔节,如果文件為空(大小為0)鹅经,那么從文件流里面讀取數(shù)據(jù)時會失敗。此時需要從鍵盤讀取屏幕的寬和高怎诫。然后瘾晃,需要調(diào)用下面的函數(shù),清除文件流的狀態(tài)位幻妓,否則所有后續(xù)文件操作都會失敗蹦误。
fs.clear()
移動文件寫指針的函數(shù)是 seekp(),文件頭的位置是 ios::beg。
fs.seep(ios::beg) //將文件的寫指針移動到文件頭
移動文件的讀指針的函數(shù)是 seekg()