FileOutputStream.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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-23
  7. *
  8. * */
  9. #include <ls-std/core/exception/FileOperationException.hpp>
  10. #include <ls-std/io/FileOutputStream.hpp>
  11. #include <ls-std/io/evaluator/FileExistenceEvaluator.hpp>
  12. using ls::std::core::Class;
  13. using ls::std::core::FileOperationException;
  14. using ls::std::core::type::byte_field;
  15. using ls::std::io::File;
  16. using ls::std::io::FileExistenceEvaluator;
  17. using ls::std::io::FileOutputStream;
  18. using std::ios;
  19. FileOutputStream::FileOutputStream(File &_file) : Class("FileOutputStream"), file(_file)
  20. {
  21. this->_init();
  22. }
  23. FileOutputStream::FileOutputStream(File &_file, bool _append) : Class("FileOutputStream"), append(_append), file(_file)
  24. {
  25. this->_init();
  26. }
  27. FileOutputStream::~FileOutputStream() noexcept
  28. {
  29. this->_close();
  30. }
  31. void FileOutputStream::close()
  32. {
  33. this->_close();
  34. }
  35. bool FileOutputStream::write(const byte_field &_data)
  36. {
  37. bool succeeded{};
  38. if (this->outputStream.is_open())
  39. {
  40. if (this->outputStream << _data)
  41. {
  42. succeeded = true;
  43. }
  44. }
  45. else
  46. {
  47. throw FileOperationException{"operation: write"};
  48. }
  49. return succeeded;
  50. }
  51. void FileOutputStream::_close()
  52. {
  53. if (this->outputStream.is_open())
  54. {
  55. this->outputStream.close();
  56. }
  57. }
  58. void FileOutputStream::_init()
  59. {
  60. FileExistenceEvaluator{this->file.getAbsoluteFilePath()}.evaluate();
  61. if (this->append)
  62. {
  63. this->outputStream.open(this->file.getAbsoluteFilePath(), ios::out | ios::app);
  64. }
  65. else
  66. {
  67. this->outputStream.open(this->file.getAbsoluteFilePath());
  68. }
  69. }