How can I read a whole file into a string variable

前端 未结 5 1076
别跟我提以往
别跟我提以往 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:00

    I'm not with computer,so I write a draft. You might be clear of what I say.

    func main(){
        const dir = "/etc/"
        filesInfo, e := ioutil.ReadDir(dir)
        var fileNames = make([]string, 0, 10)
        for i,v:=range filesInfo{
            if !v.IsDir() {
                fileNames = append(fileNames, v.Name())
            }
        }
    
        var fileNumber = len(fileNames)
        var contents = make([]string, fileNumber, 10)
        wg := sync.WaitGroup{}
        wg.Add(fileNumber)
    
        for i,_:=range content {
            go func(i int){
                defer wg.Done()
                buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
                defer file.Close()  
                content[i] = string(buf)
            }(i)   
        }
        wg.Wait()
    }
    

提交回复
热议问题