84 lines
1.4 KiB
Go
84 lines
1.4 KiB
Go
package files
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
func Files() {
|
|
Reading()
|
|
Writing()
|
|
}
|
|
|
|
func check(err error) {
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func Reading() {
|
|
data, err := os.ReadFile("/etc/hosts")
|
|
check(err)
|
|
|
|
fmt.Println("Contents:")
|
|
fmt.Println(string(data))
|
|
|
|
f, err := os.Open("/etc/hosts")
|
|
defer f.Close()
|
|
check(err)
|
|
|
|
bytes1 := make([]byte, 5)
|
|
n1, err := f.Read(bytes1)
|
|
check(err)
|
|
|
|
fmt.Printf("Read %d bytes: %v\n", n1, string(bytes1[:n1]))
|
|
|
|
o1, err := f.Seek(5, 0)
|
|
check(err)
|
|
bytes2 := make([]byte, 4)
|
|
n2, err := f.Read(bytes2)
|
|
check(err)
|
|
fmt.Printf("Read %d bytes @ %d: %v\n", n2, o1, string(bytes2[:n2]))
|
|
|
|
o2, err := f.Seek(5, 0)
|
|
check(err)
|
|
bytes3 := make([]byte, 4)
|
|
n3, err := io.ReadAtLeast(f, bytes3, 2)
|
|
check(err)
|
|
fmt.Printf("Read %d bytes @ %d: %v\n", n3, o2, string(bytes3))
|
|
|
|
o3, err := f.Seek(5, 0)
|
|
check(err)
|
|
br := bufio.NewReader(f)
|
|
bytes4, err := br.Peek(4)
|
|
check(err)
|
|
fmt.Printf("Read @ %d: %v\n", o3, string(bytes4))
|
|
}
|
|
|
|
func Writing() {
|
|
err := os.WriteFile("/tmp/go.files.write.txt", []byte("hello go!"), 0600)
|
|
check(err)
|
|
|
|
f, err := os.Create("/tmp/go.files.write2.txt")
|
|
check(err)
|
|
|
|
n1, err := f.Write([]byte{87, 73, 78})
|
|
check(err)
|
|
fmt.Printf("Wrote %d bytes\n", n1)
|
|
|
|
n2, err := f.WriteString(" macOS")
|
|
check(err)
|
|
fmt.Printf("Wrote %d bytes\n", n2)
|
|
|
|
f.Sync()
|
|
|
|
bw := bufio.NewWriter(f)
|
|
n3, err := bw.WriteString(" linux")
|
|
check(err)
|
|
fmt.Printf("Wrote %d bytes\n", n3)
|
|
|
|
bw.Flush()
|
|
}
|