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