CFile.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <LibCore/CFile.h>
  2. #include <errno.h>
  3. #include <fcntl.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. CFile::CFile(const StringView& filename, CObject* parent)
  7. : CIODevice(parent)
  8. , m_filename(filename)
  9. {
  10. }
  11. CFile::~CFile()
  12. {
  13. if (m_should_close_file_descriptor == ShouldCloseFileDescription::Yes && mode() != NotOpen)
  14. close();
  15. }
  16. bool CFile::open(int fd, CIODevice::OpenMode mode, ShouldCloseFileDescription should_close)
  17. {
  18. set_fd(fd);
  19. set_mode(mode);
  20. m_should_close_file_descriptor = should_close;
  21. return true;
  22. }
  23. bool CFile::open(CIODevice::OpenMode mode)
  24. {
  25. int flags = 0;
  26. if ((mode & CIODevice::ReadWrite) == CIODevice::ReadWrite) {
  27. flags |= O_RDWR | O_CREAT;
  28. } else if (mode & CIODevice::ReadOnly) {
  29. flags |= O_RDONLY;
  30. } else if (mode & CIODevice::WriteOnly) {
  31. flags |= O_WRONLY | O_CREAT;
  32. }
  33. if (mode & CIODevice::Append)
  34. flags |= O_APPEND;
  35. if (mode & CIODevice::Truncate)
  36. flags |= O_TRUNC;
  37. if (mode & CIODevice::MustBeNew)
  38. flags |= O_EXCL;
  39. int fd = ::open(m_filename.characters(), flags, 0666);
  40. if (fd < 0) {
  41. set_error(errno);
  42. return false;
  43. }
  44. set_fd(fd);
  45. set_mode(mode);
  46. return true;
  47. }