FileOutputStream.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-08-20
  6. * Changed: 2021-04-23
  7. *
  8. * */
  9. #include <ls_std/io/FileOutputStream.hpp>
  10. #include <ls_std/exception/FileNotFoundException.hpp>
  11. #include <ls_std/exception/FileOperationException.hpp>
  12. ls_std::FileOutputStream::FileOutputStream(ls_std::File &_file)
  13. : ls_std::Class("FileOutputStream"),
  14. file(_file)
  15. {
  16. this->_init();
  17. }
  18. ls_std::FileOutputStream::FileOutputStream(ls_std::File &_file, bool _append)
  19. : ls_std::Class("FileOutputStream"),
  20. append(_append),
  21. file(_file)
  22. {
  23. this->_init();
  24. }
  25. ls_std::FileOutputStream::~FileOutputStream()
  26. {
  27. this->_close();
  28. }
  29. void ls_std::FileOutputStream::close()
  30. {
  31. this->_close();
  32. }
  33. bool ls_std::FileOutputStream::write(const ls_std::byte_field &_data)
  34. {
  35. bool succeeded{};
  36. if (this->outputStream.is_open())
  37. {
  38. if (this->outputStream << _data)
  39. {
  40. succeeded = true;
  41. }
  42. }
  43. else
  44. {
  45. throw ls_std::FileOperationException{};
  46. }
  47. return succeeded;
  48. }
  49. void ls_std::FileOutputStream::_close()
  50. {
  51. if (this->outputStream.is_open())
  52. {
  53. this->outputStream.close();
  54. }
  55. }
  56. void ls_std::FileOutputStream::_init()
  57. {
  58. if (!this->file.exists())
  59. {
  60. throw ls_std::FileNotFoundException{};
  61. }
  62. else
  63. {
  64. if (this->append)
  65. {
  66. this->outputStream.open(this->file.getAbsoluteFilePath(), std::ios::out | std::ios::app);
  67. }
  68. else
  69. {
  70. this->outputStream.open(this->file.getAbsoluteFilePath());
  71. }
  72. }
  73. }