×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

How to read a whole file into a string variable in Golang?

Given a file, we have to read a whole content into a string variable in Golang.
Submitted by IncludeHelp, on December 01, 2021

To read the whole content of the file – we can use ioutil.ReadFile() function, The ReadFile() function is a library function of ioutil package. It accepts the file name as the parameter and returns the whole content as a byte slice. To store byte slice in a string variable – convert byte slice to a string using the string(byte[]).

Content of the file (file.txt):

Hello, world!
How are you?
~ IncludeHelp

Program to read a whole file into a string variable

// Golang program to read a whole file
// into a string variable

package main

import (
	"fmt"
	"io/ioutil"
)

func main() {
	filename := "file.txt"
	// Call the function ReadFile()
	// to read whole content
	content_b, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Print(err)
	}

	// Converting the content (byte slice)
	// into a 'string'
	str := string(content_b)

	// Printing the content
	fmt.Println("File's content is: ")
	fmt.Println(str)
}

Output:

File's content is: 
Hello, world!
How are you?
~ IncludeHelp

Golang FAQ »

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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