首页 > 解决方案 > 在 C++ 中实现 unix 实用程序“head”

问题描述

我正在尝试在 C++ 中实现 unix 实用程序“head”。我正在覆盖 std::stringbuf::sync 并返回 eof()。但是在 ostream 上,没有设置 eof。更好的是,如果它抛出异常就更好了。在线代码

#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;
  }
}

输出:

eof: 0 good: 1
eof: 0 good: 1
eof: 0 good: 0 // eof should be 1?

标签: c++stdiostreamunix-head

解决方案


推荐阅读