Armen's solution is the right answer, but I thought I would choose an alternative based on the idea of โโcaching jweyrich. For better or worse, it is read in the entire file when building, but only retains the position of the new line (it does not save the whole file, so it plays fine with massive files.) Then you can just call ReadNthLine, and it will jump to that line right away. and read in one line you want. On the other hand, this is only optimal if you want to get only a small part of the lines at a time, and line numbers are not known at compile time.
class TextFile { std::ifstream file_stream; std::vector<std::ifstream::streampos> linebegins; TextFile& operator=(TextFile& b) = delete; public; TextFile(std::string filename) :file_stream(filename) {
source share