How can I read a whole file into a string variable

前端 未结 5 1068
别跟我提以往
别跟我提以往 2020-11-29 19:32

I have lots of small files, I don\'t want to read them line by line.

Is there a function in Go that will read a whole file into a string variable?

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 20:22

    This is how I did it:

    package main
    
    import (
      "fmt"
      "os"
      "bytes"
      "log"
    )
    
    func main() {
       filerc, err := os.Open("filename")
       if err != nil{
         log.Fatal(err)
       }
       defer filerc.Close()
    
       buf := new(bytes.Buffer)
       buf.ReadFrom(filerc)
       contents := buf.String()
    
       fmt.Print(contents) 
    
    }    
    

提交回复
热议问题