package main
import(
"fmt"
"os"
"bufio"
"io"
"io/ioutil"
)
type ChartCount struct{
Chct int
Spacect int
Numberct int
Otherct int
}
func main() {
file,err := os.Open("./test.txt")
if err != nil {
fmt.Println("Open file fail", err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
str,err := reader.ReadString('\n')
if err == io.EOF {
break
}
fmt.Print(str)
}
content,err := ioutil.ReadFile("./test.txt")
if err != nil {
fmt.Println("Read file fail ", err)
}
fmt.Printf("%v\n", content)
fmt.Printf("%v\n", string(content))
//写文件O_CREATE文件不存在创建, O_TRUNC清空文件, O_APPEND追加, (O_RDWR | O_APPEND)读写模式 并追加
wfile,err := os.OpenFile("./test2.txt", os.O_WRONLY | os.O_CREATE, 0666)
if err != nil {
fmt.Println("Open file fail", err)
}
defer wfile.Close()
writer := bufio.NewWriter(wfile)
wstr := "hello,world\n"
for i := 0; i < 5; i++ {
writer.WriteString(wstr)
}
writer.Flush()
rcontent,_ := ioutil.ReadFile("./test2.txt")
ioutil.WriteFile("./test3.txt", rcontent, 0666) //写文件
//判断文件是否存在
isexist,iserror := filePathIsExists("./test3.txt")
if isexist {
fmt.Println("文件or路径存在")
} else {
fmt.Println("文件or路径不存在", iserror)
}
//copy文件
copyFile("./test3.txt", "./test4.log")
//统计一个文件里各个字符的个数
var ct ChartCount
ct.tj("./testCt.log")
fmt.Printf("chartct=%v,spaceCt=%v,Numberct=%v,Otherct=%v", ct.Chct, ct.Spacect, ct.Numberct, ct.Otherct)
}
func filePathIsExists (path string) (bool,error) {
_,error := os.Stat(path)
if nil == error {
return true,nil
}
if os.IsNotExist(error) {
return false,nil
}
return false,error
}
func copyFile(srcfile string, dstfile string) (written int64, err error) {
rfile,err := os.Open(srcfile)
if err != nil {
fmt.Println("open rfile fail", err)
}
reader := bufio.NewReader(rfile)
defer rfile.Close()
wfile,err := os.OpenFile(dstfile, os.O_WRONLY | os.O_CREATE, 0666)
if err != nil {
fmt.Println("open wfile fail", err)
}
defer wfile.Close()
writer := bufio.NewWriter(wfile)
return io.Copy(writer, reader)
}
func (ct *ChartCount) tj(filename string) {
file,err := os.Open(filename)
if err != nil {
fmt.Println("open rfile fail", err)
}
reader := bufio.NewReader(file)
defer file.Close()
for {
str,err := reader.ReadString('\n')
if err == io.EOF {
break
}
for _,v := range str {
switch{
case v >= 'a' && v <= 'z':
fallthrough
case v >= 'A' && v <= 'Z':
ct.Chct++
case v == ' ' || v == '\t':
ct.Spacect++
case v >= 0 || v <= 9:
ct.Numberct++
default:
ct.Otherct++
}
}
}
}
转载于:https://my.oschina.net/u/729139/blog/2876489