121 lines
No EOL
2.5 KiB
C++
121 lines
No EOL
2.5 KiB
C++
#include "FilePosixImpl.h"
|
|
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <sys/types.h>
|
|
#include <sys/stat.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <errno.h>
|
|
|
|
Status FilePosixImpl::do_open(const FileSystemPath& path, File::AccessMode accessMode)
|
|
{
|
|
int flags{0};
|
|
if (accessMode == File::AccessMode::Read)
|
|
{
|
|
flags |= O_RDONLY;
|
|
}
|
|
else
|
|
{
|
|
flags |= O_WRONLY;
|
|
flags |= O_CREAT;
|
|
}
|
|
errno = 0;
|
|
m_fd = ::open(path.str().raw(), flags);
|
|
if (m_fd < 0)
|
|
{
|
|
return Status::with_errno("Failed to open file with");
|
|
}
|
|
|
|
if (accessMode == File::AccessMode::Read)
|
|
{
|
|
m_open_for_read = true;
|
|
}
|
|
else
|
|
{
|
|
m_open_for_write = true;
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Status FilePosixImpl::do_close()
|
|
{
|
|
errno = 0;
|
|
if (const auto rc = ::close(m_fd); rc < 0)
|
|
{
|
|
Status::with_errno("Failed to close file with");
|
|
}
|
|
m_open_for_read = false;
|
|
m_open_for_write = false;
|
|
return {};
|
|
}
|
|
|
|
bool FilePosixImpl::is_ok() const
|
|
{
|
|
return m_valid;
|
|
}
|
|
|
|
bool FilePosixImpl::is_open_for_read() const
|
|
{
|
|
return m_open_for_read;
|
|
}
|
|
|
|
bool FilePosixImpl::is_open_for_write() const
|
|
{
|
|
return m_open_for_write;
|
|
}
|
|
|
|
Result<size_t> FilePosixImpl::do_read(VecBytes& bytes)
|
|
{
|
|
errno = 0;
|
|
const auto rc = ::read(m_fd, bytes.data(), bytes.capacity());
|
|
if (rc < 0)
|
|
{
|
|
const auto msg = _s("Error in read impl | ") + Error::from_errno();
|
|
return Result<size_t>(Error(msg));
|
|
}
|
|
return Result<size_t>(rc);
|
|
}
|
|
|
|
Result<size_t> FilePosixImpl::do_write(const VecBytes& bytes)
|
|
{
|
|
errno = 0;
|
|
const auto rc = ::write(m_fd, bytes.data(), bytes.size());
|
|
if (rc < 0)
|
|
{
|
|
const auto msg = _s("Error in write impl | ") + Error::from_errno();
|
|
return Result<size_t>(Error(msg));
|
|
}
|
|
return Result<size_t>(rc);
|
|
}
|
|
|
|
Result<size_t> FilePosixImpl::do_write(const Vector<char>& bytes, int size)
|
|
{
|
|
errno = 0;
|
|
int rc = 0;
|
|
if (size > -1)
|
|
{
|
|
rc = ::write(m_fd, bytes.data(), size);
|
|
}
|
|
else
|
|
{
|
|
rc = ::write(m_fd, bytes.data(), bytes.size());
|
|
}
|
|
if (rc < 0)
|
|
{
|
|
const auto msg = _s("Error in write impl | ") + Error::from_errno();
|
|
return Result<size_t>(Error(msg));
|
|
}
|
|
return Result<size_t>(rc);
|
|
}
|
|
|
|
Status FilePosixImpl::update_size()
|
|
{
|
|
struct stat buf;
|
|
if (const auto rc = ::fstat(m_fd, &buf); rc != 0)
|
|
{
|
|
return Status::with_errno("Failed to get size with fstat");
|
|
}
|
|
m_size = buf.st_size;
|
|
return {};
|
|
} |