C++ ifstream error using string as opening file path.
Change ifstream file(filename); to ifstream file(filename.c_str()); Because the constructor for an ifstream takes a const char*, not a string pre-C++11.
Change ifstream file(filename); to ifstream file(filename.c_str()); Because the constructor for an ifstream takes a const char*, not a string pre-C++11.
According to cplusplus.com: failbit is generally set by an input operation when the error was related to the internal logic of the operation itself, so other operations on the stream may be possible. While badbit is generally set when the error involves the loss of integrity of the stream, which is likely to persist even … Read more
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
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
NO This is what RAII is for, let the destructor do its job. There is no harm in closing it manually, but it’s not the C++ way, it’s programming in C with classes. If you want to close the file before the end of a function you can always use a nested scope. In the … Read more