新手警报开始!
我不太确定如何做到这一点--我想做一个“文件分块”,我从一个二进制文件中抓取固定的分片,以便稍后作为学习项目上传。
我目前有这个:
type (
fileChunk []byte
fileChunks []fileChunk
)
func NumChunks(fi os.FileInfo, chunkSize int) int {
chunks := fi.Size() / int64(chunkSize)
if rem := fi.Size() % int64(chunkSize) != 0; rem {
chunks++
}
return int(chunks)
}
// left out err checks for brevity
func chunker(filePtr *string) fileChunks {
f, err := os.Open(*filePtr)
defer f.Close()
// create the initial container to hold the slices
file_chunks := make(fileChunks, 0)
fi, err := f.Stat()
// show me how big the original file is
fmt.Printf("File Name: %s, Size: %d\n", fi.Name(), fi.Size())
// let's partition it into 10000 byte pieces
chunkSize := 10000
chunks := NumChunks(fi, chunkSize)
fmt.Printf("Need %d chunks for this file", chunks)
for i := 0; i < chunks; i++ {
b := make(fileChunk, chunkSize) // allocate a chunk, 10000 bytes
n1, err := f.Read(b)
fmt.Printf("Chunk: %d, %d bytes read\n", i, n1)
// add chunk to "container"
file_chunks = append(file_chunks, b)
}
fmt.Println(len(file_chunks))
return file_chunks
}这一切都很好,但是如果我的fize大小是31234字节,那么我最终会得到三个充满文件前30000字节的切片,最后的“块”将由1234个“文件字节”组成,然后“填充”到10000字节的块大小-我希望“剩余”文件块([]字节)的大小为1234,而不是全部容量-正确的方法是什么?在接收端,我会将所有的片段“缝合”在一起,以重新创建原始文件。
发布于 2013-11-16 00:06:21
您需要重新划分剩余的区块,使其仅为最后读取的区块的长度:
n1, err := f.Read(b)
fmt.Printf("Chunk: %d, %d bytes read\n", i, n1)
b = b[:n1]这将对所有块进行重新切片。通常,对于所有非剩余块,n1将为10000,但不能保证。文档上写着"Read从文件中读取最多 len(b)字节的“。所以时时刻刻关注n1是件好事。
https://stackoverflow.com/questions/20004134
复制相似问题