ADVERTISEMENT
ADVERTISEMENT

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!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.