1. 程式人生 > >檔案流作為類成員變數的初始化方式

檔案流作為類成員變數的初始化方式

ifstream繼承於istream,實現高層檔案流輸入(input)操作,它能讀取檔案中的資料到變數,可以用於讀檔案,其預設的openmode是in。

ofstream繼承於ostream,實現高層檔案流輸出(output)操作,它將資料資訊寫入到檔案,可以用於寫檔案,其預設的openmode是out。

fstream繼承於iostream,實現高層檔案流輸出(output)/輸出(input)操作,它能實現檔案的讀寫功能,是何種功能取決於openmode的組合。

openmode取值及功能如下:

作為區域性變數初始化

//方式一:
std::fstream fs("test.txt
", std::ios::in); //方式二: std::fstream fs; fs.open("test.txt", std::ios::in);

作為成員函式初始化

當檔案流作為類成員時,其初始化只能是初始化列表方式,即構造物件時檔案,不能在建構函式體中進行操作,否則檔案開啟失敗。

檔案操作時的兩個注意事項:

  1. 判斷檔案流是否正確開啟,呼叫is_open()
  2. 析構前確保斷開檔案流和檔案的關聯,呼叫close()
#include <string>
#include <fstream>
#include <iostream>

class
CWriter { public: //初始化列表方式 CWriter(const std::string &strPath, std::ios_base::openmode mode=std::ios::out|std::ios::trunc): m_path(strPath), m_file(strPath.c_str()) { } //初始化列表方式 CWriter(const char* pPath, std::ios_base::openmode mode=std::ios::out
|std::ios::trunc): m_path(pPath), m_file(pPath) { } ~CWriter() { //析構時關閉檔案流 if (is_file_open()) { m_file.close(); } } bool is_file_open() { return m_file.is_open(); } std::string GetPath() { return m_path; } void AddLog(const char* pMsg) { m_file << pMsg << "\n"; } private: std::string m_path; std::fstream m_file; }; int main() { CWriter file("test.txt"); std::cout << file.GetPath() << "\n"; if (file.is_file_open()) { std::cout << "file open ok\n"; } else { std::cout << "file open error\n"; return -1; } file.AddLog("1234"); file.AddLog("1234"); return 0; }