Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cstring>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. class BufferedWriter {
  7. public:
  8. char buffer[16];
  9. std::size_t filled;
  10.  
  11. BufferedWriter() {
  12. std::fill(this->buffer, this->buffer + sizeof(this->buffer), 0);
  13.  
  14. this->filled = 0;
  15. }
  16.  
  17. std::size_t write(const char* bytes, const size_t length) {
  18. if (length > sizeof(this->buffer) - filled) {
  19. std::size_t total = this->flush() + length;
  20.  
  21. std::cout << std::string(bytes, length);
  22.  
  23. return total;
  24. } else {
  25. std::strncpy(this->buffer + filled, bytes, length);
  26.  
  27. this->filled += length;
  28.  
  29. return 0;
  30. }
  31. }
  32.  
  33. std::size_t flush() {
  34. if (this->filled == 0) {
  35. return 0;
  36. }
  37.  
  38. std::cout << std::string(this->buffer, this->filled);
  39.  
  40. std::size_t total = this->filled;
  41.  
  42. this->filled = 0;
  43.  
  44. std::fill(this->buffer, this->buffer + sizeof(this->buffer), 0);
  45.  
  46. return total;
  47. }
  48. };
  49.  
  50. int main(int argc, char** argv) {
  51. BufferedWriter writer;
  52.  
  53. writer.write("hello\n", 6);
  54.  
  55. writer.write("world\n", 6);
  56.  
  57. writer.write("12345678\n", 9);
  58.  
  59. writer.write("lol\n", 4);
  60.  
  61. std::cout << "all writes made, flushing the buffer..." << std::endl;
  62.  
  63. writer.flush();
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement