The example in this article describes how the go language splits a file by a specified block size. Share to everyone for your reference. Specifically as follows:
Copy Code code as follows:
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)
Up to 1m per copy
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))
Write a file
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)
}
I hope this article will help you with your go language program.