Add files
This commit is contained in:
parent
89d977af8f
commit
ff58a428ff
83
files/files.go
Normal file
83
files/files.go
Normal file
@ -0,0 +1,83 @@
|
||||
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()
|
||||
}
|
6
main.go
6
main.go
@ -33,7 +33,8 @@ package main
|
||||
// import "git.sangeeth.dev/gobyexample/numberparsing"
|
||||
// import "git.sangeeth.dev/gobyexample/url"
|
||||
// import "git.sangeeth.dev/gobyexample/sha"
|
||||
import "git.sangeeth.dev/gobyexample/base64"
|
||||
// import "git.sangeeth.dev/gobyexample/base64"
|
||||
import "git.sangeeth.dev/gobyexample/files"
|
||||
|
||||
func main() {
|
||||
// runes.Runes()
|
||||
@ -69,5 +70,6 @@ func main() {
|
||||
// numberparsing.NumberParsing()
|
||||
// url.Url()
|
||||
// sha.Sha()
|
||||
base64.Base64()
|
||||
// base64.Base64()
|
||||
files.Files()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user