×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to write and read data from a text file

Here, we are going to learn how to write and read data from a text file in Golang (Go Language)?
Submitted by Nidhi, on April 05, 2021 [Last updated : March 04, 2023]

How to write and read data from a text file in Golang?

Problem Solution:

In this program, we will create a text file and save text data into the specified text file. After that, we will read data from the text file and print data on the console screen.

Program/Source Code:

The source code to write and read data from a text file is given below. The given program is compiled and executed successfully.

Golang code to write and read data from a text file

// Golang program to Write and Read data
// from a text file

package main

import "fmt"
import "os"
import "io/ioutil"

func WriteData() {
	file, err := os.Create("Sample.txt")
	if err != nil {
		fmt.Println("Unable to open file: %s", err)
	}

	len, err := file.WriteString("Hello World")

	if err != nil {
		fmt.Println("Unable to write data: %s", err)
	}
	file.Close()

	fmt.Printf("%d character written successfully into file", len)
}

func ReadData() {
	textData, err := ioutil.ReadFile("Sample.txt")
	if err != nil {
		fmt.Println("Unable to read data: %s", err)
	}
	fmt.Printf("\nData in file: %s", textData)
}

func main() {
	WriteData()
	ReadData()
}

Output:

11 character written successfully into file
Data in file: Hello World

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt, os packages then we can use a function related to the fmt and os package.

In the main() function, we created two user defined functions ReadData() and WriteData().

The WriteData() function is used to create a text file "Sample.txt" using os.Create() function and write text data into file using WriteString() file. The WriteString() function returns the number of character written into the file.

The ReadData() function is used to read data from the existing text file and print the data on the console screen.

Golang File Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.