Created
August 8, 2013 10:12
-
-
Save gintenlabo/6183430 to your computer and use it in GitHub Desktop.
get line from FILE*
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <cstring> | |
#include <cerrno> | |
#include <cstdio> | |
#include <cstdlib> | |
#include <stdexcept> | |
#include <boost/optional.hpp> | |
boost::optional<std::string> get_line(std::FILE* fp) { | |
std::string s; | |
for (;;) { | |
char buf[256]; | |
if (!std::fgets(buf, sizeof(buf), fp)) { | |
if (std::feof(fp)) { | |
if (s.empty()) { | |
return boost::none; | |
} else { | |
return std::move(s); | |
} | |
} | |
throw std::runtime_error(std::strerror(errno)); | |
} | |
std::size_t n = std::strlen(buf); | |
if (n > 0 && buf[n-1] == '\n') { | |
--n; | |
} | |
s.append(buf, n); | |
if (n < sizeof(buf) - 1) { | |
return std::move(s); | |
} | |
} | |
} | |
int main() { | |
while (auto line_ = get_line(stdin)) { | |
auto& line = *line_; | |
std::puts(line.c_str()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment