go语言对文件按照指定块大小进行分割的方法
程序员文章站
2023-02-16 22:27:55
本文实例讲述了go语言对文件按照指定块大小进行分割的方法。分享给大家供大家参考。具体如下:
复制代码 代码如下:
import (
// "bu...
本文实例讲述了go语言对文件按照指定块大小进行分割的方法。分享给大家供大家参考。具体如下:
复制代码 代码如下:
import (
// "bufio"
"flag"
"fmt"
"io"
"os"
)
import "strconv"
var infile *string = flag.string("f", "null", "please input a file name or dir.")
var size *string = flag.string("s", "0", "please input a dst file size.")
//func datacopy(file *os.file, file *os.file)
func splitfile(file *os.file, size int) {
finfo, err := file.stat()
if err != nil {
fmt.println("get file info failed:", file, size)
}
fmt.println(finfo, size)
//每次最多拷贝1m
bufsize := 1024 * 1024
if size < bufsize {
bufsize = size
}
buf := make([]byte, bufsize)
num := (int(finfo.size()) + size - 1) / size
fmt.println(num, len(buf))
for i := 0; i < num; i++ {
copylen := 0
newfilename := finfo.name() + strconv.itoa(i)
newfile, err1 := os.create(newfilename)
if err1 != nil {
fmt.println("failed to create file", newfilename)
} else {
fmt.println("create file:", newfilename)
}
for copylen < size {
n, err2 := file.read(buf)
if err2 != nil && err2 != io.eof {
fmt.println(err2, "failed to read from:", file)
break
}
if n <= 0 {
break
}
//fmt.println(n, len(buf))
//写文件
w_buf := buf[:n]
newfile.write(w_buf)
copylen += n
}
}
return
}
func main() {
flag.parse()
if *infile == "null" {
fmt.println("no file to input")
return
}
file, err := os.open(*infile)
if err != nil {
fmt.println("failed to open:", *infile)
}
defer file.close()
size, _ := strconv.atoi(*size)
splitfile(file, size*1024)
}
希望本文所述对大家的go语言程序设计有所帮助。