檔案流(fstream/ifstream/ofstream)作為類成員變數的初始化方式
阿新 • • 發佈:2019-01-03
檔案流介紹
在標準模板庫中,常見的檔案流物件有fstream、ifstream、ofstream三種,我們可以用檔案流的方式去操作檔案,比如寫檔案和讀檔案,檔案流類繼承圖如下:
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);
當檔案流作為類成員時,其初始化只能是初始化列表方式,即構造物件時檔案,不能在建構函式體中進行操作,否則檔案開啟失敗。
檔案操作時的兩個注意事項:
- 判斷檔案流是否正確開啟,呼叫is_open()
- 析構前確保斷開檔案流和檔案的關聯,呼叫close()
檔案流應用demo
#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;
}
執行結果:
當前目錄下新生成test.txt檔案,其內容是如下:
1234
1234