Golang之IO操作初接触
fmt包的使用
import (
"fmt"
"os"
)
fmt.Println("hello")
fmt.Print("hello")
fmt.Println()
fmt.Printf("%v\n", "hello")
str := fmt.Sprintf("float %f", 3.14159)
fmt.Println(str)
fmt.Fprintln(os.Stdout, "A\n")
基本io接口
import (
"fmt"
"io"
"strings"
)
func sampleReadFromString() {
bytes, _ := ReadFrom(strings.NewReader("from string"), 8)
fmt.Println(string(bytes))
}
func sampleReadStdin() {
fmt.Println("please input from stdin: ")
bytes, _ := ReadFrom(os.Stdin, 11)
fmt.Println(string(bytes))
}
func sampleReadFile() {
file, _ := os.Open("main.go")
defer file.Close()
bytes, _ := ReadFrom(file, 9)
fmt.Println(string(bytes))
}
func ReadFrom(reader io.Reader, num int) ([]byte, error) {
p := make([]byte, num)
n, err := reader.Read(p)
if n > 0 {
return p[:n], nil
}
return p, err
}
缓存IO
func main() {
reader := strings.NewReader("hello world")
bufReader := bufio.NewReader(reader)
bytes, _ := bufReader.Peek(8)
fmt.Println(string(bytes))
fmt.Println(bufReader.Buffered())
str, _ := bufReader.ReadString(' ')
fmt.Println(str, bufReader.Buffered())
w := bufio.NewWriter(os.Stdout)
fmt.Fprint(w, "Hello ")
fmt.Fprint(w, "world")
w.Flush()
}
计算文件行数
func main () {
if len(os.Args) < 2 {
return
}
filename := os.Args[1]
file, err := os.Open(filename)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
reader := bufio.NewReader(file)
var line int
for {
_, isPrefix, err := reader.ReadLine()
if err != nil {
break
}
if !isPrefix {
line++
}
}
fmt.Println(line)
}
打开App,阅读手记