标准设备文件操作
package main
import (
"os"
)
func main() {
os.Stdout.WriteString("hello world") //相当于fmt.Println
}
磁盘文件操作
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func WriteFile(path string) {
f, err := os.Create(path)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
for i := 0; i <= 10; i++ {
tmp := fmt.Sprintf("i = %d
", i)
_, er := f.WriteString(tmp)
if er != nil {
fmt.Println(er)
}
}
}
func ReadFile(path string) {
f, err := os.Open(path)
if err != nil {
fmt.Println(err)
}
defer f.Close()
buf := make([]byte, 1024*2)
n, er := f.Read(buf)
if er != nil {
fmt.Println(er)
}
fmt.Println(string(buf[:n]))
}
//一行一行的读取
func ReadLine(path string) {
f, err := os.Open(path)
if err != nil {
fmt.Println(err)
}
defer f.Close()
r := bufio.NewReader(f)
for {
buf, e := r.ReadBytes('
')
if e != nil {
if e == io.EOF {
break
}
fmt.Println(e)
}
fmt.Printf("%s", buf)
}
}
func main() {
path := "./demo.txt"
WriteFile(path)
// ReadFile(path)
// ReadLine(path)
}