
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read a File into a String in Go
To read a file into a string, we need to make use of the io/ioutil package that Go's standard library provides us with.
Inside the io/ioutil package, there's a function called ReadFile() which is used to open a file and then convert its contents into a slice of bytes, and if for some reason, it isn't able to do so, then it will return an error too.
Here is the syntax of the ReadLine() function.
func ReadFile(filename string) ([]byte, error)
It should be noted that if the above function has made a successful call, then it will return err == nil, not err == EOF. It is so, as the above function reads the whole file, it doesn't treat an EOF from Read as an error.
We will get a slice of byte, i.e., []byte instead of a string as the result, and to convert it into a string, we need to do basic type conversion.
Let's first consider a case where we have a file called gocode.txt that contains the following content.
This file contains some random text.
Now, let's see the code where we will open this file and then convert it into a string.
Example 1
Consider the code shown below.
package main import ( "fmt" "io/ioutil" "log" ) func main() { fileContent, err := ioutil.ReadFile("gocode.txt") if err != nil { log.Fatal(err) } // Convert []byte to string text := string(fileContent) fmt.Println(text) }
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
This file contains some random text.
If for some reason, we change the name of the file to something other than gocode.txt, then the code will produce an error.
Example 2
Consider the code shown below.
package main import ( "fmt" "io/ioutil" "log" ) func main() { fileContent, err := ioutil.ReadFile("gocode.txt") if err != nil { log.Fatal(err) } // Convert []byte to string text := string(fileContent) fmt.Println(text) }
Output
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
2021/10/11 12:05:46 open gocode.txt: no such file or directory exit status 1