How can I read the whole file into a string variable

I have many small files, I do not want to read them line by line.

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

+114
string file go readfile
Nov 22 '12 at 13:52
source share
5 answers

Use ioutil.ReadFile :

 func ReadFile(filename string) ([]byte, error) 

ReadFile reads a file named filename and returns its contents. A successful call returns err == nil, not err == EOF. Since the ReadFile reads the entire file, it does not consider the EOF from Read as an error to be reported.

You will get []byte instead of string . This can be converted if really needed:

 s := string(buf) 
+181
Nov 22
source share

If you want the content to be string , then a simple solution is to use the ReadFile function from the io/ioutil . This function returns a bytes fragment that you can easily convert to string .

 package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("file.txt") // just pass the file name if err != nil { fmt.Print(err) } fmt.Println(b) // print the content as 'bytes' str := string(b) // convert content to a 'string' fmt.Println(str) // print the content as a 'string' } 
+27
Aug 07 '16 at 5:41
source share

I think the best thing you can do if you are really worried about the efficiency of concatenating all these files is to copy them all to the same buffer.

 buf := bytes.NewBuffer(nil) for _, filename := range filenames { f, _ := os.Open(filename) // Error handling elided for brevity. io.Copy(buf, f) // Error handling elided for brevity. f.Close() } s := string(buf.Bytes()) 

This opens each file, copies its contents to buf, and closes the file. Depending on your situation, you may not need to convert it, the last line is just to show that buf.Bytes () has the data you are looking for.

+12
Nov 22 '12 at 15:09
source share

Here 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) } 
+2
Apr 17 '17 at 10:48
source share

I am not with a computer, so I am writing a draft. You can be clear from what I am saying.

 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() } 
0
Feb 01 '19 at 7:40
source share



All Articles