c++ stringstream 读写文件两种方法

2020-04-27  本文已影响0人  _backtrack_

读写文件

#include "iostream"
#include "fstream"
#include "sstream"

using namespace std;


/**
 * method 1  write to file
 * @param filepath
 * @param src
 */
inline void write0(std::string filepath, std::string src) {

    fstream file(filepath, ios::binary | ios::out);
    file << src;
    file.close();

}

/**
 * method 1 read from file
 * @param filepath
 * @return
 */
inline stringstream read0(std::string filepath) {
    ifstream fin(filepath, ios::binary | ios::out);
    stringstream out;
    copy(istreambuf_iterator<char>(fin),
         istreambuf_iterator<char>(),
         ostreambuf_iterator<char>(out));
    fin.close();
    return out;
}

/**
 * method 2  write to file
 * @param filepath
 * @param src
 */
inline void write(std::string filepath, basic_stringbuf<char, char_traits<char>, allocator<char>> *src) {
    fstream fo(filepath);
    fo << src;
    fo.close();
}

/**
 * method 2 read from file
 * @param filepath
 * @return
 */
inline stringstream read(std::string filepath) {
    ifstream fi(filepath);
    stringstream out;
    out << fi.rdbuf();
    fi.close();
    return out;
}


int main() {
    std::stringstream iss("hello method 1");
    cout << iss.str() << endl;

    write0("hello.txt", iss.str());
    stringstream stream0;
    stream0 = read0("hello.txt");
    cout << "method 1 -> read from file ->" << stream0.str() << endl;


    /**
     * method 2 test
     */
    iss.str("hello method 2");
    cout << iss.str() << endl;
    
    write("hello.txt", iss.rdbuf());
    stringstream stream1;
    stream1 = read("hello.txt");
    cout << "method 2 -> read from file ->" << stream1.str() << endl;


    return 0;
}


运行结果如下

hello method 1
method 1 -> read from file ->hello method 1
hello method 2
method 2 -> read from file ->hello method 2

参考

https://stdcxx.apache.org/doc/stdlibug/34-4.html

上一篇下一篇

猜你喜欢

热点阅读