68 lines
1.6 KiB
C++
68 lines
1.6 KiB
C++
|
#include <fcntl.h>
|
||
|
#include <os/File.h>
|
||
|
#include <sys/syscall.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
namespace os
|
||
|
{
|
||
|
File::File(Badge<File>)
|
||
|
{
|
||
|
}
|
||
|
|
||
|
File::~File()
|
||
|
{
|
||
|
if (m_fd >= 0) close(m_fd);
|
||
|
}
|
||
|
|
||
|
Result<SharedPtr<File>> File::construct(StringView path, int flags, mode_t mode)
|
||
|
{
|
||
|
auto file = TRY(adopt_shared(new (std::nothrow) File({})));
|
||
|
|
||
|
long rc = syscall(SYS_open, path.chars(), flags, mode);
|
||
|
int fd = TRY(Result<int>::from_syscall(rc));
|
||
|
|
||
|
file->m_fd = fd;
|
||
|
|
||
|
return file;
|
||
|
}
|
||
|
|
||
|
Result<SharedPtr<File>> File::open(StringView path, OpenMode flags)
|
||
|
{
|
||
|
return construct(path, (int)flags, 0);
|
||
|
}
|
||
|
|
||
|
Result<SharedPtr<File>> File::open_or_create(StringView path, OpenMode flags, mode_t mode)
|
||
|
{
|
||
|
return construct(path, (int)flags | O_CREAT, mode);
|
||
|
}
|
||
|
|
||
|
Result<SharedPtr<File>> File::create(StringView path, OpenMode flags, mode_t mode)
|
||
|
{
|
||
|
return construct(path, (int)flags | (O_CREAT | O_EXCL), mode);
|
||
|
}
|
||
|
|
||
|
Result<usize> File::raw_read(u8* buf, usize length)
|
||
|
{
|
||
|
long rc = syscall(SYS_read, m_fd, buf, length);
|
||
|
return Result<usize>::from_syscall(rc);
|
||
|
}
|
||
|
|
||
|
Result<usize> File::raw_write(const u8* buf, usize length)
|
||
|
{
|
||
|
long rc = syscall(SYS_write, m_fd, buf, length);
|
||
|
return Result<usize>::from_syscall(rc);
|
||
|
}
|
||
|
|
||
|
Result<void> File::write(StringView str)
|
||
|
{
|
||
|
TRY(raw_write((const u8*)str.chars(), str.length()));
|
||
|
|
||
|
return {};
|
||
|
}
|
||
|
|
||
|
void File::set_close_on_exec()
|
||
|
{
|
||
|
fcntl(m_fd, F_SETFD, FD_CLOEXEC);
|
||
|
}
|
||
|
}
|