Read a File to String

· 162 words · 1 minute read

This is a matching post to “Writing to a File” and explains how to simply get the contents of a file as text and print it to screen.

There are different ways to achieve this in Go - all valid. In this guide though we’ve gone for the simple approach. Using ioutil makes this easy for us by not having to worry about closing files or using buffers. At the cost though of not having flexibility over which parts of the file we need.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
    "fmt"
    "io/ioutil"
    "log"
)

func main() {

    // Read entire file content, giving us little control but
    // making it very simple. No need to close the file.
    content, err := ioutil.ReadFile("golangcode.txt")
    if err != nil {
        log.Fatal(err)
    }

    // Convert []byte to string and print to screen
    text := string(content)
    fmt.Println(text)
}

read from a file

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!