读文件:
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("test.log")
if err != nil {
fmt.Print(err)
}
fmt.Println(b)
str := string(b)
fmt.Println(str)
}
写文件:
package main
import (
"io/ioutil"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("test.txt", d1,0644)
check(err)
}
使用os进行读写文件
首先要注意的就是两个打开文件的方法:
func Open
func Open(name string) (*File, error)
Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.
读文件:
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
func OpenFile
需要提供文件路径、打开模式、文件权限
func OpenFile(name string, flag int, perm FileMode) (*File, error)
OpenFile is the generalized open call;