In Go, the ReadFile()
function of the ioutil
library is used to read data from a file. Using ioutil
makes file reading easier as you don’t have to worry about closing files or using buffers.
To read an entire file into a variable, use the ReadFile
function from the ioutil
library. This is the most basic type of file reading that can be required. The code below shows how to do this.
package mainimport ("fmt""io/ioutil")func main() {data, err := ioutil.ReadFile("file.txt")if err != nil {fmt.Println("File reading error", err)return}fmt.Println("Contents of file:")fmt.Println(string(data))}
The err
variable gets an error description if an error occurs while reading the file. In the case of any problem, the error gets displayed to the user.
Sometimes, it’s not feasible to read the whole file in one go, especially when the file size is too large. So, instead, we can read the file in chunks of set bytes. The following code reads the file in 3-byte chunks.
package mainimport ("bufio""flag""fmt""log""os")func main() {fptr := flag.String("fpath", "file.txt", "file path to read from")flag.Parse()f, err := os.Open(*fptr)if err != nil {log.Fatal(err)}defer func() {if err = f.Close(); err != nil {log.Fatal(err)}}()r := bufio.NewReader(f)b := make([]byte, 3)for {n, err := r.Read(b)if err != nil {fmt.Println("Error reading file:", err)break}fmt.Println(string(b[0:n]))}}
f
.r
) until the end-of-file is reached; then, the bytes are printed.We can also read each line in a file separately. This method reduces strain on the memory as the entire file will not be read in one go.
package mainimport ("bufio""flag""fmt""log""os")func main() {fptr := flag.String("fpath", "file.txt", "file path to read from")flag.Parse()f, err := os.Open(*fptr)if err != nil {log.Fatal(err)}defer func() {if err = f.Close(); err != nil {log.Fatal(err)}}()s := bufio.NewScanner(f)for s.Scan() {fmt.Println(s.Text())}err = s.Err()if err != nil {log.Fatal(err)}}
f
.Free Resources