From 43ea9acb421baa6f3379af9ae4508dfb4bf339ab Mon Sep 17 00:00:00 2001 From: siddharth ravikumar Date: Fri, 25 Nov 2022 20:18:44 -0500 Subject: file: add `ReadFile` --- file/file.go | 10 ++++++++++ file/file_test.go | 22 ++++++++++++++++++++++ file/testdata/life.txt | 1 + 3 files changed, 33 insertions(+) create mode 100644 file/file_test.go create mode 100644 file/testdata/life.txt diff --git a/file/file.go b/file/file.go index 4267b10..9bb974d 100644 --- a/file/file.go +++ b/file/file.go @@ -24,6 +24,16 @@ func Read(f *os.File) ([]byte, error) { return bs, nil } +func ReadFile(path string) ([]byte, error) { + f, err := os.Open(path) + if err != nil { + return []byte{}, err + } + defer f.Close() + + return Read(f) +} + func Write(f *os.File, content []byte) error { n, err := f.Write(content) if n != len(content) { diff --git a/file/file_test.go b/file/file_test.go new file mode 100644 index 0000000..143b072 --- /dev/null +++ b/file/file_test.go @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: ISC +// Copyright © 2022 siddharth + +package file + +import ( + "bytes" + "testing" +) + +func TestReadFile(t *testing.T) { + expectedBS := []byte("42 is the answer.\n") + bs, err := ReadFile("testdata/life.txt") + if err != nil { + t.Errorf("read file: %v", err) + return + } + if !bytes.Equal(bs, expectedBS) { + t.Errorf("read content: '%s' != '%s'", bs, expectedBS) + return + } +} diff --git a/file/testdata/life.txt b/file/testdata/life.txt new file mode 100644 index 0000000..c1b8e71 --- /dev/null +++ b/file/testdata/life.txt @@ -0,0 +1 @@ +42 is the answer. -- cgit v1.2.3