c++ - 在 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?
解决方案
推荐阅读
- ruby-on-rails - Rswag 和 Rspec:URL 参数的未定义方法
- python - 使用特征工具创建“时间窗口特征”
- amazon-web-services - maven settings.xml 拉环境变量?
- python - 有没有办法为新的 venv 升级 pip?
- python - Scrapy 脚本无异常运行,但没有收集到数据
- php - 无法获取表单处理页面以将数据传递到 php 我的管理员
- database - 在 MongoDB 中添加文档标识符有什么好处?
- html - Bootstrap 4 Flex Box 圣杯布局和主/细节工作流程
- amazon-web-services - 机构可以通过哪些方式将其 AWS VPC 连接到 Internet?
- python - 如何隐藏使用 matplotlib 绘制子图时显示的数据表