In the tutorial, we will learn how to read and write a file in Go Lang.
Golang offers a vast inbuilt library that can be used to perform read and write operations on files. In order to read from files on the local system, the io/ioutil module is put to use. The io/ioutil module is also used to write content to the file.
How to read and write a file in GoLang
Here is a Golang program to read and write the files.
Let's create a file named go_example.go and add the following content to it:
// Golang program to read and write the files
package main
// importing the packages
import (
"fmt"
"io/ioutil"
"log"
"os"
)
func CreateFile() {
fmt.Printf("Writing to a file in Go lang\n")
// in case an error is thrown it is received
// by the err variable and Fatalf method of
// log prints the error message and stops
// program execution
file, err := os.Create("sample.txt")
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
// Defer is used for purposes of cleanup like
// closing a running file after the file has
// been written and main //function has
// completed execution
defer file.Close()
// len variable captures the length
// of the string written to the file.
len, err := file.WriteString("My first fav programming languge is Go Lang \nMy second fav programming languge is Java \nMy third fav programming languge is Python\n")
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
// Name() method returns the name of the
// file as presented to Create() method.
fmt.Printf("\nFile Name: %s", file.Name())
fmt.Printf("\nLength: %d bytes", len)
}
func ReadFile() {
fmt.Printf("\n\nReading a file in Go lang\n")
fileName := "sample.txt"
// The ioutil package contains inbuilt
// methods like ReadFile that reads the
// filename and returns the contents.
data, err := ioutil.ReadFile("sample.txt")
if err != nil {
log.Panicf("failed reading data from file: %s", err)
}
fmt.Printf("\nFile Name: %s", fileName)
fmt.Printf("\nSize: %d bytes", len(data))
fmt.Printf("\nData\n: %s", data)
}
// main function
func main() {
CreateFile()
ReadFile()
}
Output:
G:\GoLang\examples>go run go_example.go Writing to a file in Go lang File Name: sample.txt Length: 131 bytes Reading a file in Go lang File Name: sample.txt Size: 131 bytes Data : My first fav programming languge is Go Lang My second fav programming languge is Java My third fav programming languge is Python
After executing above program, open the 'sample.txt' file and you should able to see the content of the file as below:
My first fav programming languge is Go Lang My second fav programming languge is Java My third fav programming languge is Python
Comments
Post a Comment