dourang8305 2014-04-24 05:46
浏览 35
已采纳

io.Copy()清除阅读器内容

    package main

    import (
        "fmt"
        "io"
        "io/ioutil"
        "os"
    )

    func main() {
        file, err := os.Open("HelloWorld")
        if nil != err {
            fmt.Println(err)
        }
        defer file.Close()

        fileTo, err := os.Create("fileTo")
        if nil != err {
            fmt.Println(err)
        }
        defer file.Close()

        _, err = io.Copy(fileTo, file)
        if nil != err {
            fmt.Println(err)
        }

        fileByteOne, err := ioutil.ReadAll(file)
        if nil != err {
            fmt.Println(err)
        }

        fmt.Println(fileByteOne)
    }

io.Copy() will erase the file content, the output is :

[]

Copy(dst Writer, src Reader) copies from src to dst, it will erase the src content. Is there any way to avoid erasing?

  • 写回答

2条回答 默认 最新

  • dqwr32867 2014-04-24 05:55
    关注

    io.Copy(fileTo, file) will erase the file content

    It won't. But it will move the read position to EOF, meaning the next ioutil.ReadAll() will start at ... EOF.

    You could close it and re-open 'file'before your ioutil.ReadAll().

    By the way, you have two defer file.Close() instances: the second one should be defer fileTo.Close().
    Or, simpler, reset it with a SectionReader.Seek(), as suggested by PeterSO's answer.

     _, err = file.Seek(0, os.SEEK_SET)
    

    It is also illustrated in GoByExamples Reading Files:

    There is no built-in rewind, but Seek(0, 0) accomplishes this.

    (os.SEEK_SET is define in os constants, as 0)

    const SEEK_SET int = 0 // seek relative to the origin of the file
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?