簡體   English   中英

我應該在 C++ 中使用 string 或 ostringstream 或 stringstream 作為 fileIO

[英]Should I use string or ostringstream or stringstream for fileIO in C++

我想使用fstream s 使用 C++ 寫入大文件的開頭。
我想出的方法是把整個數據寫到一個臨時文件中,然后寫到原始文件中,再把tmp文件中的數據復制到原始文件中。

我想創建一個緩沖區,它將數據從原始文件帶到 tmp 文件,反之亦然。
該過程適用於所有stringostringstreamstringstream 我希望數據復制能夠快速進行,並且消耗最少的 memory。

帶有string示例

void write(std::string& data)
{
    std::ifstream fileIN("smth.txt");
    std::ofstream fileTMP("smth.txt.tmp");
    std::string line = "";

    while(getline(fileIN, line))
        fileTMP << line << std::endl;

    fileIN.close();
    fileTMP.close();

    std::ifstream file_t_in("smth.txt.tmp"); // file tmp in
    std::ofstream fileOUT("smth.txt");
    fileOUT << data;

    while(getline(file_t_in, line)
        fileOUT << line << std::endl;

    fileOUT.close();
    file_t_in.close();

    std::filesystem::remove("smth.txt.tmp");
}

我應該為此使用string還是ostringstreamstringstream

使用一個比另一個有什么優勢?

假設至少有一些操作並且您沒有復制兩次相同的數據以以未更改的文件結束,可能的改進(恕我直言)是:

  • 不要在循環內使用std::endl ,而只能使用'\n'"\n" std::endl確實寫了一個行尾,但也強制對底層 stream 進行刷新,這在循環中是無用且昂貴的。
  • 您的代碼將數據復制了兩次。 如果可能的話,通過復制(就像您的代碼當前所做的那樣)構建一個臨時文件,然后刪除舊文件並使用原始名稱重命名臨時文件,效率會更高。 這樣你只復制一次數據,因為重命名文件是一種廉價的操作。

您不需要手動復制,有std::filesystem::copy

如果你真的想使用文件流進行復制,你可以使用一行代碼: output_stream << input_stream.rdbuf(); .

如果你真的想用循環手動復制,它不必是基於行的。 使用固定大小的緩沖區。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM