CFile.cpp 1.2 KB

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