登录
首页 >  Golang >  Go问答

在 Golang 中实现文件覆盖操作

来源:stackoverflow

时间:2024-02-26 15:18:17 477浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《在 Golang 中实现文件覆盖操作》,聊聊,我们一起来看看吧!

问题内容

如何通过分块读取大文件并按顺序处理每个块,然后将结果块覆盖到它的确切来源(文件的相同位置或偏移量)?

例如:我想读取 4096 字节块的 1 gb 文件,对其执行一些操作,例如删除特殊字符(!@#$...),然后将结果替换为原始内容,然后转到下一个 4096 块到达文件末尾。

我不想将所有文件加载到内存中,块的顺序和偏移量非常重要,主要问题是从同一文件中顺序读取和覆盖块。

我刚刚做了什么:

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
}

正确答案


只需以读写模式打开文件,然后使用 File.WriteAt() 写回修改后的切片即可。

请注意,File.Read() 可能不会填满整个切片,特别是如果您位于文件末尾(并且没有更多数据),因此存储并使用它返回的读取字节数:

n, err := file.read(current)
// ...
processedchunk := process(current[:n])

不要忘记关闭文件!

这是完整的解决方案:

file, err := os.OpenFile("file.txt", os.O_RDWR, 0755)
if err != nil {
    log.Println(err)
}
defer file.Close()

current := make([]byte, 4096)

for pos := int64(0); ; {
    n, err := file.Read(current)
    if err != nil {
        if err == io.EOF {
            break
        }
        log.Fatal(err)
    }

    processedChunk := process(current[:n])
    if _, err := file.WriteAt(processedChunk, pos); err != nil {
        log.Fatal(err)
    }

    pos += int64(n)
}

今天关于《在 Golang 中实现文件覆盖操作》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>