In the past file I could get data from FPGA by QT, but the data is not segmented. So I use golang to make a tool in order to add split.
package main
import(
"io"
"os"
"log"
"fmt"
"time"
"bufio"
"os/user"
"strings"
)
// set readbuffer size
const bufferSize = 1024 * 1024
func splitHex(hexStr string) string {
// structure the result strings
var result strings.Builder
// handle two elements each cycle
for i := 0; i < len(hexStr); i += 2 {
result.WriteString(hexStr[i : i+2])
// add " " to split
result.WriteRune(' ')
}
return result.String()
}
func processChunk(chunk []byte, chunkStr string, WriteFilePath string) {
// 处理缓冲区中的每个16进制字符
// fmt.Println(splitHex(chunkStr))
file, err := os.OpenFile(WriteFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer file.Close()
// write split data into file
_, err = file.WriteString(splitHex(chunkStr))
if err != nil {
panic(err)
}
}
func main(){
// get current datetime
t := time.Now()
time := t.Format("2006-01-02 15-04-05")
log.Println("current time: ",time)
// get current 'user' home path
currentUser , err := user.Current()
if err != nil{
log.Println("get current user Info failed")
}
log.Println(currentUser.HomeDir)
// input file path by user
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Enter the transfer file")
scanner.Scan()
text := scanner.Text()
FilePath := currentUser.HomeDir + "\\Desktop\\FPGA_USB\\" + text
fmt.Println("Enter the write file name")
scanner.Scan()
WriteFilePath := scanner.Text()
// open the file
file , err := os.Open(FilePath)
if err != nil{
log.Println("open file failed")
}
defer file.Close()
log.Println("open ", FilePath, " OK!")
// create a bufio.Reader to read file
reader := bufio.NewReader(file)
buffer := make([]byte, bufferSize)
for {
// read a piece of data
n, err := reader.Read(buffer)
if n > 0 {
// convert byte slices to strings
chunkStr := string(buffer[:n])
processChunk(buffer[:n], chunkStr, WriteFilePath)
}
if err != nil {
if err == io.EOF {
// read all file finished
break
}
fmt.Printf("Error reading file: %s\n", err)
}
}
log.Println("Transfer finished!!!")
}
I use buffer to get data and split them and write into a file.