CFile.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. ASSERT(!m_filename.is_null());
  26. int flags = 0;
  27. if ((mode & CIODevice::ReadWrite) == CIODevice::ReadWrite) {
  28. flags |= O_RDWR | O_CREAT;
  29. } else if (mode & CIODevice::ReadOnly) {
  30. flags |= O_RDONLY;
  31. } else if (mode & CIODevice::WriteOnly) {
  32. flags |= O_WRONLY | O_CREAT;
  33. }
  34. if (mode & CIODevice::Append)
  35. flags |= O_APPEND;
  36. if (mode & CIODevice::Truncate)
  37. flags |= O_TRUNC;
  38. if (mode & CIODevice::MustBeNew)
  39. flags |= O_EXCL;
  40. int fd = ::open(m_filename.characters(), flags, 0666);
  41. if (fd < 0) {
  42. set_error(errno);
  43. return false;
  44. }
  45. set_fd(fd);
  46. set_mode(mode);
  47. return true;
  48. }