簡體   English   中英

C++如何為多個文件編寫一個ifstream?

[英]C++ how to write a ifstream for multiple files?

所以我有幾個文件,它們形成了一個隨機的行數,所以讓我們稱它們為 file1、file2、file3 等等。 我想要做的是創建一個 istream 類,它將所有文件作為一個流。 我得到的一件事不是對 std::istream 進行子類化,而是重新實現 streambuf。 我的問題是:我將如何解決這個問題 - 我如何能夠從多個文件中讀取而不將它們全部存儲在內存中?

是否可以制作一個讀取多個文件的istream

是的,但你必須自己做。 您可以通過擴展std::istream來實現您自己的istream類,然后實現它定義的方法:

class custom_istream : public std::istream {
    std::ifstream underlying; 
    //... implement methods
};

std::istream的接口足夠靈活,可以讓你做你想做的事。 但是,實現std::istream需要大量工作,因為您必須實現整個接口。

有更簡單的解決方案嗎?

如果您只需要std::istream提供的功能的一個子集,您可以編寫自己的類。

例如,如果您只需要能夠從文件中讀取行,下面的類將適用於多個文件:

class MultiFileReader {
    std::ifstream filestream; 
    std::ios_base::openmode mode;  
    size_t file_index = 0; 
    std::vector<std::string> filenames; 
    void open_next_file() {
        file_index++; 
        filestream = std::ifstream(filenames.at(file_index), mode); 
    }
   public:
    MultiFileReader(std::vector<std::string> const& files, std::ios_base::openmode mode)
      : filestream(files[0], mode), mode(mode) {}
    // Checks if there's no more files to open, and no more to read
    // in the current file
    bool hasMoreToRead() {
        if(file_index == filenames.size()) return false;
        if(file_index + 1 == filenames.size()) 
            return not filestream.eof(); 
        return true;
    }
    std::string read_line() {
        if(not hasMoreToRead()) {
            throw std::logic_error("No more to read"); 
        }
        // If at the end of the file, open the next file
        if(filestream.eof()) {
            open_next_file(); 
        }
        else {
            std::string line; 
            std::getline(filestream, line);
            return line; 
        }
    }
};  

暫無
暫無

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

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