Go chan write to a file structure

chan requires two processes, a write, a read, are separated,

package main

import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
"sync"
"time"
)

type (
cdnfileinfo struct {
filename string
buf []byte
sync.RWMutex
wrtype int
serr string
}
fileWrok interface {
isDirExtxit(path string) int
Writefile(b *backset)
Readfile(b *backset)
Randfilename(b *backset)
}
fileWorkint interface {
Randfilename(b *backset)
}

Workout struct {
fileWrok
}
workInt struct {
fileWorkint
}
backset struct {
ducks chan cdnfileinfo
}

)

func (fi *Workout) isDirExtxit(path string) int {
finfo, er := os.Stat(path)
if er != nil {
return 0
}
if finfo.IsDir() {
return 1
} else {
return 2
}

}
func (fi *workInt)Randfilename(b *backset) {
for {
duck := cdnfileinfo{
filename: "D:/Text/log" + fmt.Sprint(rand.Intn(999999)) + ".txt",
wrtype: 2,
buf: []byte("添加测试"),
}
fmt.Printf("type:%d filename:%s \n", duck.wrtype, duck.filename)
b.ducks <- duck
time.Sleep(time.Second)
}
}


func (fi *Workout) Writefile(b *backset) {
for {
duck, _ := <-b.ducks
pos := strings.LastIndex(duck.filename, "/")
path := duck.filename[0 : pos+1]
switch fi.isDirExtxit(path) {
case 0:
{
er := os.Mkdir(path, os.ModePerm)
if er != nil {
continue
}
}
case 2:
{
continue
}

}

f, er := os.OpenFile(duck.filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if er != nil {

}
fbuf := bufio.NewWriter(f)
fbuf.Write(duck.buf)
fbuf.Flush()
fmt.Printf("type:%d filename:%s \n", duck.wrtype, duck.filename)
}
}
func (fi *Workout) Readfile(b *backset) error {
duck,_:= <- b.ducks
_, er := os.Stat(duck.filename)
if er != nil {
return nil
}
sf, er := os.Open(duck.filename)
if er != nil {
return er
}
rbuf := bufio.NewReader(sf)
n, er := rbuf.Read(duck.buf)
if er != nil {
return nil
}
if n == 0 {
return fmt.Errorf("读取文件为空")
}
return nil
}

func main() {
wa := new(sync.WaitGroup)

p := new(workInt)
c := new(Workout)
b := &backset{
ducks: make(chan cdnfileinfo),
}

wa.Add(2)
go func() {
p.Randfilename(b)
wa.Done()
}()
go func() {
c.Writefile(b)
wa.Done()
}()

wa.Wait()

}

Guess you like

Origin www.cnblogs.com/pykill/p/12025152.html