Reading from a File
This lesson provides coding examples and their explanations for reading from a file.
Reading data from a file #
Files in Go are represented by pointers to objects of type os.File
, also called file handles. The standard input os.Stdin
and output os.Stdout
we used in the previous lesson are both of type *os.File
. This is used in the following program:
package mainimport ("bufio""fmt""io""os")func main() {inputFile, inputError := os.Open("input.dat")if inputError != nil {fmt.Printf("An error occurred on opening the inputfile\n" +"Does the file exist?\n" +"Have you got access to it?\n")return // exit the function on error}defer inputFile.Close()inputReader := bufio.NewReader(inputFile)for {inputString, readerError := inputReader.ReadString('\n')if readerError == io.EOF {return}fmt.Printf("The input was: %s", inputString)}}
In the code above, at line 10, a call to os.Open
creates a variable inputFile
of type *os.File
: this is a struct that represents an open file descriptor (a filehandle). The Open
function accepts a parameter filename
of type string (here as input.dat) and opens the file in read-only mode.
This can, of course, result in an error when the file does not exist or the program does not have sufficient rights to open the file: inputFile, inputError = os.Open("input.dat")
. From line 11 to line 17, we are handling the errors.
The defer
keyword is very useful for ensuring that the opened file will also be closed at the end of the function with defer inputFile.Close()
at line 18. Here is a code snippet, where this is used in a function data()
: