Skip to content

Commit

Permalink
Use seek enums and show other seek methods (#524)
Browse files Browse the repository at this point in the history
* Use seek whence values

* Add examples of seeking with other methods
  • Loading branch information
kauppie authored Apr 29, 2024
1 parent 7958694 commit baadeda
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 14 deletions.
19 changes: 14 additions & 5 deletions examples/reading-files/reading-files.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,37 @@ func main() {

// You can also `Seek` to a known location in the file
// and `Read` from there.
o2, err := f.Seek(6, 0)
o2, err := f.Seek(6, io.SeekStart)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: ", n2, o2)
fmt.Printf("%v\n", string(b2[:n2]))

// Other methods of seeking are relative to the
// current cursor position,
_, err = f.Seek(4, io.SeekCurrent)
check(err)

// and relative to the end of the file.
_, err = f.Seek(-10, io.SeekEnd)
check(err)

// The `io` package provides some functions that may
// be helpful for file reading. For example, reads
// like the ones above can be more robustly
// implemented with `ReadAtLeast`.
o3, err := f.Seek(6, 0)
o3, err := f.Seek(6, io.SeekStart)
check(err)
b3 := make([]byte, 2)
n3, err := io.ReadAtLeast(f, b3, 2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))

// There is no built-in rewind, but `Seek(0, 0)`
// accomplishes this.
_, err = f.Seek(0, 0)
// There is no built-in rewind, but
// `Seek(0, io.SeekStart)` accomplishes this.
_, err = f.Seek(0, io.SeekStart)
check(err)

// The `bufio` package implements a buffered
Expand Down
4 changes: 2 additions & 2 deletions examples/reading-files/reading-files.hash
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
5351edae47bb2f2c9b5d4b9682b8176beb0c24e5
DF2Wo8nDKaF
754d3ce4873b6f8f1c81364bfcf5fedb17020c11
upAKv1DPNMp
39 changes: 32 additions & 7 deletions public/reading-files

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit baadeda

Please sign in to comment.