Skip to content

Instantly share code, notes, and snippets.

@gintenlabo
Created August 8, 2013 10:12
Show Gist options
  • Save gintenlabo/6183430 to your computer and use it in GitHub Desktop.
Save gintenlabo/6183430 to your computer and use it in GitHub Desktop.
get line from FILE*
#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