FileOutputStream.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Co-Author: Claude Sonnet 4.6 (LLM)
  4. * Company: Lynar Studios
  5. * E-Mail: webmaster@lynarstudios.com
  6. * Created: 2020-08-20
  7. * Changed: 2026-06-23
  8. *
  9. * */
  10. #include <exception>
  11. #include <iostream>
  12. #include <ls-std/core/exception/FileOperationException.hpp>
  13. #include <ls-std/io/FileOutputStream.hpp>
  14. #include <ls-std/io/evaluator/FileExistenceEvaluator.hpp>
  15. using ls::standard::core::Class;
  16. using ls::standard::core::FileOperationException;
  17. using ls::standard::core::type::byte_field;
  18. using ls::standard::io::File;
  19. using ls::standard::io::FileExistenceEvaluator;
  20. using ls::standard::io::FileOutputStream;
  21. using std::cout;
  22. using std::endl;
  23. using std::exception;
  24. using std::ios;
  25. FileOutputStream::FileOutputStream(const File &_file) : Class("FileOutputStream"), file(_file)
  26. {
  27. this->_init();
  28. }
  29. FileOutputStream::FileOutputStream(const File &_file, const bool _append) : Class("FileOutputStream"), append(_append), file(_file)
  30. {
  31. this->_init();
  32. }
  33. FileOutputStream::~FileOutputStream() noexcept
  34. {
  35. try
  36. {
  37. this->_close();
  38. }
  39. catch (const exception &_exception)
  40. {
  41. cout << "could not close file output stream: " << _exception.what() << endl;
  42. }
  43. }
  44. void FileOutputStream::close()
  45. {
  46. this->_close();
  47. }
  48. bool FileOutputStream::write(const byte_field &_data)
  49. {
  50. bool succeeded{};
  51. if (this->outputStream.is_open())
  52. {
  53. if (this->outputStream << _data)
  54. {
  55. succeeded = true;
  56. }
  57. }
  58. else
  59. {
  60. throw FileOperationException{"operation: write"};
  61. }
  62. return succeeded;
  63. }
  64. void FileOutputStream::_close()
  65. {
  66. if (this->outputStream.is_open())
  67. {
  68. this->outputStream.close();
  69. }
  70. }
  71. void FileOutputStream::_init()
  72. {
  73. FileExistenceEvaluator{this->file.getAbsoluteFilePath()}.evaluate();
  74. if (this->append)
  75. {
  76. this->outputStream.open(this->file.getAbsoluteFilePath(), ios::out | ios::app);
  77. }
  78. else
  79. {
  80. this->outputStream.open(this->file.getAbsoluteFilePath());
  81. }
  82. }