In this section, we're going to see how to read the entire contents of a file. We will create a new file called names
and I have a bunch of names, for instance, Tarik
, Guney
, Michael
, John
, and Montana
. We are going to read this file. We're going to use the io
utility package that provides a read file function and it accepts the path of the file, that is, names.txt
. It returns two things: the actual content of the file and errors. If no error occurs, we're going to convert the contentBytes
to a string
representation first. Now let's write the content to the console using the following code:
package main import ( "io/ioutil" "fmt" ) func main(){ contentBytes, err := ioutil.ReadFile("names.txt") if err == nil{
var contentStr string = string(contentBytes) fmt.Println(contentStr) } }
On running the code in the terminal by using go run main.go
command, you'll obtain the following output:
Thus, you can see that we have read all the names...