FileOutputStream.cpp 1.9 KB

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