GO - READING FILE
So, in the previous tutorial, we have created a file named 'myfirstfile.txt', with the below contents,
Now, To delete a File, we need to import the 'io/ioutil' package.
Let us see, how can we read the above file in Go.
How to read the entire file?
Example :
package main
import "fmt"
import "io/ioutil"
func main() {
str, error := ioutil.ReadFile("myfirstfilego.txt")
if (error != nil) {
fmt.Println("Error occurred while reading the file.")
}
fmt.Printf("%s",str)
}
Output :
In a huge pond,
there lived many fish.
They were arrogant and
never listened to anyone.In this pond,
there also lived
a kind-hearted crocodile.
-
So we have used the 'ReadFile()' Function from the 'ioutil' package to read the entire contents of the file.
str = ioutil.ReadFile("myfirstfilego.txt")
And initialised the contents of the file in a variable, 'str'. The contents of the file is stored in bytes in 'str'.
-
After that we have used the 'fmt.Printf' statement to print the contents of 'str' after converting it to String.
fmt.Printf("%s",str)