package main
import (
"fmt"
"os"
"bufio"
"io/ioutil"
)
//错误处理方法
func handle(why string,e error){
if e!=nil{
fmt.Println(why,"错误为:",e)
}
}
func main() {
//读文件方式一
/*file, e := os.OpenFile("./1.txt",os.O_RDONLY,0754)
handle("文件打开失败!", e)
defer file.Close()
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('\n')
if err == io.EOF{
break
}
handle("文件读取失败!", err)
fmt.Println(str)
}
fmt.Println("文件读取完毕!")*/
//读文件方式二
/*bytes, e := ioutil.ReadFile("./1.txt")
handle("文件读取失败!",e)
fmt.Println(bytes)
fmt.Println(string(bytes))*/
file, i := os.OpenFile("./1.txt", os.O_WRONLY|os.O_APPEND, 0761)
handle("打开文件失败!", i)
defer file.Close()
writer := bufio.NewWriter(file)
name := "heiasdasdasdasdasdasdasdasdasdasdasdashei "
_, err := writer.WriteString(name)
writer.Flush()
handle("文件写入失败!",err)
fmt.Println("写入成功")
bytes, e := ioutil.ReadFile("./1.txt")
handle("文件读取失败!",e)
fmt.Println(bytes)
fmt.Println(string(bytes))
}
打开文件时,第二个参数可以控制,打开文件的方式,比如os.APPEND是文件写入时,在末尾添加