package main
import (
"fmt"
"os"
"strconv"
"strings"
)
var A=0
var fileSize int64
func main() {
var fileRootPath = "/root/goProject/file"
name := fileRootPath + "/testwritefile"+strconv.Itoa(A)+".txt"
fileSize=1024*1024
content := "a"
for ;; {
if A>=5 {
break
}
isFileBool:=isFile(name)
if isFileBool{
fhandler, _ := os.Stat(name)
if fhandler.Size()<=fileSize {
writeWithIoutil(name, content)
}else {
A++
name = fileRootPath + "/testwritefile"+strconv.Itoa(A)+".txt"
writeWithIoutil(name, content)
}
}else {
writeWithIoutil(name, content)
}
}
}
//使用ioutil.WriteFile方式写入文件,是将[]byte内容写入文件,如果content字符串中没有换行符的话,默认就不会有换行符
func writeWithIoutil(name, content string) {
fd, _ := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fd_content := strings.Join([]string{content, "\n"}, "")
buf := []byte(fd_content)
fd.Write(buf)
fd.Close()
}
func isFile(filename string) bool {
fhandler, err := os.Stat(filename)
if !(err == nil || os.IsExist(err)) {
return false
} else if fhandler.IsDir() {
return false
}
return true
}