Appendix A. understanding os.openfile: Opening Files

image

Some programs need to write data to files, not just read data. Throughout the book, when we’ve wanted to work with files, you had to create them in your text editor for your programs to read. But some programs generate data, and when they do, they need to be able to write data to a file.

We used the os.OpenFile function to open a file for writing earlier in the book. But we didn’t have space then to fully explore how it worked. In this appendix, we’ll show you everything you need to know in order to use os.OpenFile effectively!

Understanding os.OpenFile

In Chapter 16, we had to use the os.OpenFile function to open a file for writing, which required some rather strange-looking code:

image

Back then, we were focused on writing a web app, so we didn’t want to take too much time out to fully explain os.OpenFile. But you’ll almost certainly need to use this function again in your Go-writing career, so we added this appendix to take a closer look at it.

When you’re trying to figure out how a function works, it’s always good to start with its documentation. In your terminal, run go doc os OpenFile (or search for the "os" package documentation in your browser).

Its arguments are a string filename, an int “flag,” and an os.FileMode ...

Get Head First Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.