一分鐘徹底搞懂fstream下的讀寫操作

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string path = "D/ssss/reflection.hpp";
    //這情況下,默認下是std::ios_base::in讀入 trun:在打開時捨棄流的內容
    std::ifstream open_file(path, std::ios_base::ate | std::ios_base::binary);
    std::size_t size = open_file.tellg();
    open_file.seekg(std::ios_base::beg);
    std::string buffer;
    buffer.resize(size);

    open_file.read((char*)buffer.c_str(), size);
    open_file.close();


    std::string write_path = "D:/reflection1.hpp";
    //app:每次寫入,指針移動到末尾,也就是追加 out:寫入,binary:二進流模式 trun:在打開時捨棄流的內容
    std::ofstream write_file(write_path, std::ios_base::binary|std::ios_base::app);
    for (int i =0;i<2;i++){
        write_file.write(buffer.c_str(), buffer.size());
    }

    write_file.close();

    //默認可讀寫模式
    //std::fstream fs;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章