1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <bits/stdc++.h> using namespace std;
class RecordBuffer { public: explicit RecordBuffer(int size, string file): file_(file), buffer_size_(size), buffer_(new char[size]) {}
~RecordBuffer() { FlushBuffer(); cout << "Destructed after flushing" << endl; } void WriteRecord(const char *data, int size) { if (!IsAvailable(size)) { FlushBuffer(); } WriteToBuffer(data, size); } void WriteToBuffer(const char *data, int size) { assert(IsAvailable(size)); memcpy(buffer_.get() + buffer_used_, data, size); buffer_used_ += size; } void FlushBuffer() { if (buffer_used_ == 0) return; ofstream f(file_, ios::app); f << string(buffer_.get(), buffer_used_) << endl; this_thread::sleep_for(chrono::seconds(3)); f.close(); buffer_used_ = 0; } bool IsAvailable(int size) { return buffer_size_ - buffer_used_ >= size; } unique_ptr<char[]> buffer_; int buffer_size_; int buffer_used_{0}; string file_; };
int main() { RecordBuffer rb(16, "output.txt"); string s{"zxcvbnm"}; for (int i = 0; i < 20; ++i) { rb.WriteRecord(s.data(), s.size()); } }
|