Go Program to Read a File

Go Program to Read a File

In Go programming, io package is used to work with file operations.

ReadFile function in io package is used to read the file data.

Sample Go program explains how to read content, converting as string and printing the file content..

package main                                                               	 
                                                                           	 
import (                                                                   	 
	"fmt"                                                                  	 
	"io/ioutil"                                                            	 
)                                                                          	 
                                                                           
// Reading file content	 
func ReadFile() string {                                                   	 
	msg,_ := ioutil.ReadFile("test.txt")                                   	 
	return string(msg)                                                     	 
}                                                                          	 
                                                                           	 
func main() {                                                              	 
	var msg string                                                         	 
                                                                           	 
	msg = ReadFile()                                                       	 
                                                                           	 
	fmt.Println("File content 'test.txt': "+ msg)                          	 
                                                                           	 
} 
Output:
$ go build read-file.go
$ ./read-file
File content 'test.txt': codingpointer.com!