-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_iter.go
55 lines (45 loc) · 1.4 KB
/
file_iter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"fmt"
"io"
"github.com/enetx/g"
"github.com/enetx/g/f"
)
func main() {
// Example 1: Reading and processing lines
r := g.
NewFile("text.txt"). // Open a new file with the specified name "text.txt"
Lines() // Read the file line by line
// switch pattern
switch {
case r.IsOk():
r.Ok().
Skip(3). // Skip the first 3 lines
Exclude(f.Zero). // Exclude lines that are empty or contain only whitespaces
Dedup(). // Remove consecutive duplicate lines
Map(g.String.Upper). // Convert each line to uppercase
Range(func(s g.String) bool {
if s.Contains("COULD") { // Check if the line contains "COULD"
return false
}
fmt.Println(s)
return true
})
case r.IsErr():
fmt.Println("err:", r.Err())
}
// Example 2: Reading and processing chunks
offset := int64(10) // Initialize offset
g.NewFile("text.txt").
Seek(offset, io.SeekStart).Ok(). // Seek to 10 bytes from the beginning of the file
Chunks(3). // Read the file in chunks of 3 bytes
Unwrap(). // Unwrap the Result type to get the underlying iterator
Inspect(func(s g.String) { // Update the offset based on the length of each chunk
offset += int64(s.Bytes().Len())
}).
ForEach(func(s g.String) { // For each chunk, print it
fmt.Print(s)
})
// Print the final offset
fmt.Println(offset)
}