How does ifstream’s eof() work?

-1 is get‘s way of saying you’ve reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) – avoid -1, it’s a magic number. (Although the other one is a bit verbose – you can always just call istream::eof) The EOF flag is only set once a read tries to read past the … Read more

Getting std :: ifstream to handle LF, CR, and CRLF?

As Neil pointed out, “the C++ runtime should deal correctly with whatever the line ending convention is for your particular platform.” However, people do move text files between different platforms, so that is not good enough. Here is a function that handles all three line endings (“\r”, “\n” and “\r\n”): std::istream& safeGetline(std::istream& is, std::string& t) … Read more

Fast textfile reading in c++

Updates: Be sure to check the (surprising) updates below the initial answer Memory mapped files have served me well1: #include <boost/iostreams/device/mapped_file.hpp> // for mmap #include <algorithm> // for std::find #include <iostream> // for std::cout #include <cstring> int main() { boost::iostreams::mapped_file mmap(“input.txt”, boost::iostreams::mapped_file::readonly); auto f = mmap.const_data(); auto l = f + mmap.size(); uintmax_t m_numLines = … Read more

How to extract a multiline text segment between two delimiters under a certain heading from a text file using C++ [closed]

After taking a closer look at reading text files in C++, I settled on this passable but most likely far from ideal solution: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string TextFile; cout << “Enter the wordlist to search:” << “\n”; getline(cin, TextFile); string Search; int Offset = 0; int … Read more