CFile.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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)
  7. : m_filename(filename)
  8. {
  9. }
  10. CFile::~CFile()
  11. {
  12. if (m_should_close_file_descriptor == ShouldCloseFileDescription::Yes && mode() != NotOpen)
  13. close();
  14. }
  15. bool CFile::open(int fd, CIODevice::OpenMode mode, ShouldCloseFileDescription should_close)
  16. {
  17. set_fd(fd);
  18. set_mode(mode);
  19. m_should_close_file_descriptor = should_close;
  20. return true;
  21. }
  22. bool CFile::open(CIODevice::OpenMode mode)
  23. {
  24. int flags = 0;
  25. if ((mode & CIODevice::ReadWrite) == CIODevice::ReadWrite) {
  26. flags |= O_RDWR | O_CREAT;
  27. } else if (mode & CIODevice::ReadOnly) {
  28. flags |= O_RDONLY;
  29. } else if (mode & CIODevice::WriteOnly) {
  30. flags |= O_WRONLY | O_CREAT;
  31. }
  32. if (mode & CIODevice::Append)
  33. flags |= O_APPEND;
  34. if (mode & CIODevice::Truncate)
  35. flags |= O_TRUNC;
  36. if (mode & CIODevice::MustBeNew)
  37. flags |= O_EXCL;
  38. int fd = ::open(m_filename.characters(), flags, 0666);
  39. if (fd < 0) {
  40. set_error(errno);
  41. return false;
  42. }
  43. set_fd(fd);
  44. set_mode(mode);
  45. return true;
  46. }