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条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?