FileOutputStream.cpp 1.7 KB

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