User Program Communication

Read from Text File in Go

Used to input a file into the program.

fileData, err := ioutil.ReadFile("path to file") //assuming the io/ioutil package is imported
//file contents are stored in the fileData variable as a byte array


The ReadFile method returns the contents of the file and an error (if necessary) in that order. The file is returned as a byte array.

package main

import (

func main() {
    names, err := ioutil.ReadFile("names.txt")
    check(err) //error checking
    fmt.Println("The names in the file are: ", string(names))

See Also

ioutil - The Go Programming Language

Add to Slack

< Commenting   |   Write to FIle >

© 2019 SyntaxDB. All Rights Reserved.