文件流作为类成员变量的初始化方式

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;
}

猜你喜欢

转载自www.cnblogs.com/tianzeng/p/10211797.html