Skip to content

Commit 29fb5dc

Browse files
committed
Add examples/basic/ioop/offsetwrite.go
1 parent 36280c0 commit 29fb5dc

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

examples/basic/ioop/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
| multiread.go | ioop_multiread | io.MultiReaderを利用して複数のファイルを一気に読み込むサンプルです。 |
1111
| teeread.go | ioop_tee_read | io.TeeReader を利用したサンプルです。 |
1212
| sectionread.go | ioop_section_read | io.SectionReader を利用したサンプルです。 |
13+
| offsetwrite.go | ioop_offset_write | io.OffsetWriter を利用したサンプルです。 |

examples/basic/ioop/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
2121
m["ioop_multireader"] = MultiRead
2222
m["ioop_tee_read"] = TeeRead
2323
m["ioop_section_read"] = SectionRead
24+
m["ioop_offset_write"] = OffsetWrite
2425
}

examples/basic/ioop/offsetwrite.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package ioop
2+
3+
import (
4+
"bufio"
5+
"io"
6+
"os"
7+
"path/filepath"
8+
9+
"github.com/devlights/gomy/errs"
10+
"github.com/devlights/gomy/output"
11+
)
12+
13+
// OffsetWrite は、io.OffsetWriter を利用したサンプルです。
14+
//
15+
// io.OffsetWriter は、io.WriterAt インターフェースを実装しているものを要求する。
16+
//
17+
// os.File が io.WriterAt を実装している。
18+
//
19+
// # REFERENCES
20+
// - https://pkg.go.dev/io@go1.22.2#OffsetWriter
21+
// - https://cs.opensource.google/go/go/+/go1.22.2:src/io/io.go;l=570
22+
func OffsetWrite() error {
23+
w, err := os.CreateTemp(os.TempDir(), "trygolang")
24+
if err != nil {
25+
return err
26+
}
27+
28+
fstat := errs.Drop(w.Stat())
29+
{
30+
defer w.Close()
31+
32+
bufW := bufio.NewWriter(w)
33+
bufW.WriteString("helloworld こんにちは世界")
34+
bufW.Flush()
35+
36+
offW := io.NewOffsetWriter(w, 11) // "helloworld " の次の位置(つまり「こ」)にオフセットを設定
37+
offW.Write([]byte("コンニチハ"))
38+
39+
offW.Seek(int64(15), io.SeekStart) // "コンニチハ" の次の位置(つまり「世」)にシークポジションをセット
40+
offW.Write([]byte("セカイ"))
41+
}
42+
43+
data := errs.Drop(os.ReadFile(filepath.Join(os.TempDir(), fstat.Name())))
44+
output.Stdoutl("[offW]", string(data))
45+
46+
return nil
47+
48+
/*
49+
$ task
50+
task: [build] go build .
51+
task: [run] ./try-golang -onetime
52+
53+
ENTER EXAMPLE NAME: ioop_offset_write
54+
55+
[Name] "ioop_offset_write"
56+
[offW] helloworld コンニチハセカイ
57+
58+
59+
[Elapsed] 165.78µs
60+
*/
61+
62+
}

0 commit comments

Comments
 (0)