修复后的代码如下:

package main

import (
	"bytes"
	"encoding/binary"
	"io/ioutil"
	"os"
)

// fixFiles2 合并文件2
func fixFiles2(fileList []string, fileOutPath string) {
	// 先进行获取文件长度 和音频文件长度 写入到Head byte数组中!
	var totalLength int64
	length := make([]int64, len(fileList))
	for i, file := range fileList {
		info, err := os.Stat(file)
		if err != nil {
			panic(err)
		}
		length[i] = info.Size() - 44

		if length[i] < 0 {
			panic("Invalid file length")
		}

		totalLength += length[i]
	}

	// 设置总长度
	fileLength := make([]byte, 4)
	binary.BigEndian.PutUint32(fileLength, uint32(totalLength+36))

	dataLength := make([]byte, 4)
	binary.BigEndian.PutUint32(dataLength, uint32(totalLength))

	// 数组反转
	fileLength = reverseBytes(fileLength)
	dataLength = reverseBytes(dataLength)

	head := make([]byte, 44)
	byteArrayOutputStream := bytes.NewBuffer(head)

	// 进行获取头部信息
	for i, file := range fileList {
		fileBytes, err := ioutil.ReadFile(file)
		if err != nil {
			panic(err)
		}

		if i == 0 {
			copy(head, fileBytes[:44])
			copy(head[4:8], fileLength)
			copy(head[40:44], dataLength)

			// 先将头文件写进去!
			byteArrayOutputStream.Write(fileBytes[44:])
		} else {
			byteArrayOutputStream.Write(fileBytes[44:])
		}
	}

	// 进行写出文件
	err := ioutil.WriteFile(fileOutPath, byteArrayOutputStream.Bytes(), 0644)
	if err != nil {
		panic(err)
	}
}

// reverseBytes 数组反转
func reverseBytes(arr []byte) []byte {
	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
		arr[i], arr[j] = arr[j], arr[i]
	}
	return arr
}

修复的内容:

  1. 在获取文件长度时,增加了长度小于0时的判断,并抛出错误。
  2. 修复了todo标记处的错误,该错误是因为文件不存在导致的。
  3. 在写出文件时,指定了文件的权限为0644
请修复优化下面代码todo的部分:package mainimport 	bytes	encodingbinary	ioioutil	os fixFiles2 合并文件2func fixFiles2fileList string fileOutPath string 	 先进行获取文件长度 和音频文件长度 写入到Head byte数组中!	var totalLength int64	length

原文地址: http://www.cveoy.top/t/topic/h3BN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录