How to read a large file by chunking it and process each chunk sequentially then overwrite the resulted chunk to where it exactly came from(the same position or offset of file)?
e.g: i want to read 1 GB file with 4096 bytes chunk do something with it like removing the special characters(!@#$...) then, replace result with the original content and, go to the next 4096 chunk to reach the end of file.
I don't want to load all the file into memory, the order and offset of chunks is very matter and the main problem is with sequential read and overwrite chunk from the same file.
What i've just done:
func main(){
file,err := os.Open("file.xt")
if err != nil {
log.Println(err)
}
chunkSize := 4096
current := make([]byte, chunkSize)
for {
// read the file in 4096 bytes of chunk
_, err := file.Read(current)
if err != nil{
if err == io.EOF {
break
}
log.Fatal(err)
}
//
processedChunk := process(current)
// we open the same file again with O_APPEND for overwriting the content, right?
file2, err := os.OpenFile("file.txt", os.O_WRONLY|os.O_APPEND, os.ModePerm)
if err != nil {
log.Println(err)
}
// How to go ahead here with overwriting the processedChunk with currentChunk?
}
}
func process(data []byte) []byte{
// do something with the chunk
return data
}