More robust GetLine

This commit is contained in:
Jacob Dufault 2017-03-09 10:02:55 -08:00
parent 1508ac85d8
commit 7c55502fe8

View File

@ -54,11 +54,44 @@ std::vector<std::string> GetFilesInFolder(std::string folder, bool add_folder_to
return GetFilesInFolderHelper(folder, add_folder_to_path ? folder : "");
}
// http://stackoverflow.com/a/6089413
std::istream& SafeGetline(std::istream& is, std::string& t) {
t.clear();
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
// The sentry object performs various tasks,
// such as thread synchronization and updating the stream state.
std::istream::sentry se(is, true);
std::streambuf* sb = is.rdbuf();
for(;;) {
int c = sb->sbumpc();
switch (c) {
case '\n':
return is;
case '\r':
if(sb->sgetc() == '\n')
sb->sbumpc();
return is;
case EOF:
// Also handle the case when the last line has no line ending
if(t.empty())
is.setstate(std::ios::eofbit);
return is;
default:
t += (char)c;
}
}
}
std::vector<std::string> ReadLines(std::string filename) {
std::vector<std::string> result;
std::ifstream input(filename);
for (std::string line; getline(input, line); )
for (std::string line; SafeGetline(input, line); )
result.push_back(line);
return result;
@ -88,4 +121,4 @@ void Fail(const std::string& message) {
void WriteToFile(const std::string& filename, const std::string& content) {
std::ofstream file(filename);
file << content;
}
}