0

I'm trying to implement the unix utility "head" in C++. I'm overriding std::stringbuf::sync and returning eof(). But on the ostream, eof does not get set. Even better, it would be nice if it threw an exception. online code

#include <iostream>
#include <sstream>
#include <vector>

class Head : public std::stringbuf {
public:
  Head(std::size_t max) : max(max) {}

  int_type sync() override {
    if (lines.size() < max) {
      lines.push_back(str());
      str(std::string());
      return 0;
    }
    return traits_type::eof();
  }

  const std::size_t max;
  std::vector<std::string> lines;
};

int main(int, char*[]) {
  auto head = Head{2};
  std::ostream stream(&head);
  for (auto i = 0; i < 3; ++i) {
    stream << i << std::endl;
    std::cout << "eof: " << stream.eof() << " good: " << stream.good() << std::endl;
  }
}

output:

eof: 0 good: 1
eof: 0 good: 1
eof: 0 good: 0 // eof should be 1?
Aaron Frantisak
  • 543
  • 5
  • 11

0 Answers0