You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
star/generate/generate.go

96 lines
2.1 KiB
Go

2 years ago
package generate
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
"github.com/spf13/cobra"
)
var Cmd = &cobra.Command{
Use: "generate",
Short: "生成随机文件",
Long: "生成指定大小的随机文件",
Run: func(this *cobra.Command, args []string) {
sum, _ := this.Flags().GetInt("sum")
num, _ := this.Flags().GetInt("num")
cap, _ := this.Flags().GetInt("cap")
if len(args) != 1 {
this.Help()
return
}
if num <= 0 {
fmt.Println("num不合法不应该小于1")
os.Exit(2)
}
if sum < 0 {
fmt.Println("sum不合法不应该小于0")
os.Exit(2)
}
if cap <= 0 {
fmt.Println("cap不合法不应该小于1")
os.Exit(2)
}
err := FillWithRandom(args[0], num, cap, sum, func(pect float64) {
fmt.Printf("文件已处理:%f%%\r", pect)
})
if err != nil {
fmt.Println("err:" + err.Error())
}
fmt.Println("文件已处理100.0000000%")
time.Sleep(time.Millisecond * 10)
},
}
func init() {
Cmd.Flags().IntP("sum", "s", 3, "随机的种子组数")
Cmd.Flags().IntP("num", "n", 1024, "生成的文件大小")
Cmd.Flags().IntP("cap", "c", 1048576, "bufcap大小")
Cmd.MarkFlagRequired("num")
}
// FillWithRandom 随机写filesize大小的文件每次buf大小为bufcap随机bufnum个字符
func FillWithRandom(filepath string, filesize int, bufcap int, bufnum int, shell func(float64)) error {
var buf [][]byte
var buftmp []byte
rand.Seed(time.Now().Unix())
if bufnum <= 0 {
bufnum = 1
}
if bufcap > filesize {
bufcap = filesize
}
myfile, err := os.Create(filepath)
if err != nil {
return err
}
defer myfile.Close()
writer := bufio.NewWriter(myfile)
for i := 0; i < bufnum; i++ {
buftmp = []byte{}
for j := 0; j < bufcap; j++ {
buftmp = append(buftmp, byte(rand.Intn(256)))
}
buf = append(buf, buftmp)
}
sum := 0
for {
if filesize-sum < bufcap {
writer.Write(buf[rand.Intn(bufnum)][0 : filesize-sum])
sum += filesize - sum
} else {
writer.Write(buf[rand.Intn(bufnum)])
sum += bufcap
}
go shell(float64(sum) / float64(filesize) * 100)
if sum >= filesize {
break
}
}
writer.Flush()
return nil
}