zoukankan      html  css  js  c++  java
  • Go chan 结构体 写入文件

    chan 需要两个进程,一个写,一个读,是分开的,

    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 ", 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 ", 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()

    }
  • 相关阅读:
    Redis配置文件详解
    SpingBoot 定时器(跟随Application启动)
    Linux 查找哪些文件包含指定的一个或多个字符串
    帆软报表中sql中出现汉字时乱码
    mysql 匹配奇数、偶数行数据
    vs code 快捷键中英文对照
    前端学习路线汇总
    vscode: Visual Studio Code 常用快捷键1
    vue-router的router.go(n)问题?
    vue2.0 技巧汇总
  • 原文地址:https://www.cnblogs.com/pykill/p/12025152.html
Copyright © 2011-2022 走看看