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

    }
  • 相关阅读:
    Crontab中的除号(slash)到底怎么用?
    Crontab设置shell脚本开始执行时间以及结束时间
    CISCO 3750交换机堆叠
    Linux中Too many open files 问题分析和解决
    java 包装类的应用
    Java final修饰符
    Java 多态
    Java 子类初始化过程
    Java 深入变量和封装思想小结
    JaVA web服务器配置
  • 原文地址:https://www.cnblogs.com/pykill/p/12025152.html
Copyright © 2011-2022 走看看