2018年6月29日 星期五

I/O流

  • include
  • void ifstream::open(const char *filename, openmode mode=ios::in); 
    void ofstream::open(const char *filename, openmode mode=ios::out |ios::trunc);
    void fstream::open(const char *filename, openmode mode=ios::in | ios::out);
  • filename是檔案名稱,而mode決定檔案的開啟模式
  • 如果您使用ofstream來開啟檔案,若指定的檔案原先存在,則檔案會被清空,您可以使用附加方式,或是使用ifstream並指定ios::in與ios::out,即可保留原檔案的內容。

  • 如果開啟失敗則串流會傳回false,您可以使用下面的片段來判斷: 
    if(!fin) { 
        cout << "無法讀取檔案\n"; 
        // 其它處理 

    最低階的輸出與輸出函式為get()和put()函式,它們被重載(overload)多次,我們這邊介紹最基本的字元輸入與輸出,它們的函式雛型如下: 
    istream &get(char &ch); 
    ostream &put(char); 

    當讀取至檔尾時,get()函式會傳回false,也可以使用eof()函式來判斷是否讀取至檔案尾端;下面這個程式示範如何讀入一個文字檔案,並顯示在主控台上
    ios::in檔案open為輸入模式(istream default)
    ios::out檔案open為寫入(ostream default)
    ios::ate從檔案尾端輸入輸出
    ios::app在檔案尾端以append模式寫入
    ios::trunc如果檔案存在,則清除檔案內容
    ios::binary以二進位模式open檔案

沒有留言:

張貼留言

Ethereum- Learn Solidity step by step

Common Function Types: public: Anyone can call this function,but it isn't really used for any type of security per se. priv...