libos: Add a convenience function for opening a file or standard input

This commit is contained in:
apio 2023-04-26 20:41:03 +02:00
parent fb09eb97ce
commit cb28e2a385
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 16 additions and 5 deletions

View File

@ -6,14 +6,10 @@ using os::File;
static Result<void> do_cat(StringView path)
{
SharedPtr<File> f;
SharedPtr<File> f = TRY(File::open_input_file(path));
auto out = File::standard_output();
if (path == "-") f = File::standard_input();
else
f = TRY(File::open(path, File::ReadOnly));
auto buf = TRY(Buffer::create_sized(4096));
while (1)
{

View File

@ -24,6 +24,14 @@ namespace os
static Result<SharedPtr<File>> open_or_create(StringView path, OpenMode flags, mode_t mode = 0644);
static Result<SharedPtr<File>> create(StringView path, OpenMode flags, mode_t mode = 0644);
/*
If path is "-", return standard input (as is common for many CLI apps). Otherwise, open path for reading.
This function is a convenience function for CLI apps, so that they don't need to check path and open standard
input if necessary.
*/
static Result<SharedPtr<File>> open_input_file(StringView path);
static SharedPtr<File> standard_input();
static SharedPtr<File> standard_output();
static SharedPtr<File> standard_error();

View File

@ -82,6 +82,13 @@ namespace os
return construct(path, (int)flags | (O_CREAT | O_EXCL), mode);
}
Result<SharedPtr<File>> File::open_input_file(StringView path)
{
if (path == "-"_sv) return standard_input();
return construct(path, O_RDONLY, 0);
}
Result<usize> File::raw_read(u8* buf, usize length)
{
long rc = syscall(SYS_read, m_fd, buf, length);