diff --git a/apps/cat.cpp b/apps/cat.cpp index 7236fbf9..d5019b6d 100644 --- a/apps/cat.cpp +++ b/apps/cat.cpp @@ -6,14 +6,10 @@ using os::File; static Result do_cat(StringView path) { - SharedPtr f; + SharedPtr 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) { diff --git a/libos/include/os/File.h b/libos/include/os/File.h index 0f32277a..ab770058 100644 --- a/libos/include/os/File.h +++ b/libos/include/os/File.h @@ -24,6 +24,14 @@ namespace os static Result> open_or_create(StringView path, OpenMode flags, mode_t mode = 0644); static Result> 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> open_input_file(StringView path); + static SharedPtr standard_input(); static SharedPtr standard_output(); static SharedPtr standard_error(); diff --git a/libos/src/File.cpp b/libos/src/File.cpp index 9a3e5676..2f6be82a 100644 --- a/libos/src/File.cpp +++ b/libos/src/File.cpp @@ -82,6 +82,13 @@ namespace os return construct(path, (int)flags | (O_CREAT | O_EXCL), mode); } + Result> File::open_input_file(StringView path) + { + if (path == "-"_sv) return standard_input(); + + return construct(path, O_RDONLY, 0); + } + Result File::raw_read(u8* buf, usize length) { long rc = syscall(SYS_read, m_fd, buf, length);