go语言实现文件分割的方法
程序员文章站
2022-05-26 09:40:01
本文实例讲述了go语言实现文件分割的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:import (
// "bufio"...
本文实例讲述了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
}
}
// "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语言程序设计有所帮助。
上一篇: 一步步教你配置MySQL远程访问
下一篇: GO语言make()分配用法实例