You will need to read or write files in your programs almost all the time. This is a basic requirement that every programmer should have under their belts. This article will cover how to open and read files in Go using the os package.
Golang OS package
To read and write files in Go, we need to import the os package. You can import it using the import keyword as shown below:
Once imported, you can perform file operations with no errors.
os.Open()
Before using the Open() method to open and read the file, let us prepare our environment. Create a working directory:
Navigate into the directory and create a text file:
touch hello.txt
Once we have a text file to read, open it with your favorite text editor and add some content:
"Hello from the hello.txt file"
Close and save the file.
To open and read the file in go, create a go file and enter the code:
if err != nil {
log.Fatal(err)
}
Once we open the file, we can read the data of the file into a slice of bytes. We can do this using the Read method, which takes the byte size as the argument. An example is as shown:
count, err := file.Read(file_data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Read %d bytes: %q\n", count, file_data[:count])
}
In this section, we use the create a slice of bytes. We then use the Read() method to read the data of the file.
We check for errors and then determine the number of bytes we read from the file. Using the printf method, we print the content of the file.
The resulting output:
Read 29 bytes: “Hello from the hello.txt file”
As you can see, we read precisely 29 bytes from the file.
If we try to open a file that does not exist, the function returns an error as shown:
Error Output:
exit status 1
os.OpenFile()
The OpenFile() method allows you to open a file with the specified flag. Such flags include:
- O_RDONLY– Read-Only Mode.
- O_WRONLY. Opens file in Write Only mode.
- O_RDWR–Open the file in Read-Write mode.
- O_APPEND–Appends data to the file when writing.
- O_TRUNC–Truncate the file when opened, where applicable.
- O_SYNC – Open the file for synchronous I/O.
- O_CREATE – Create a file if it does not exist.
You can specify any flag when opening a file based on your requirements.
If you call the OpenFile() method with the O_CREATE flag, if the file does not exist, it is created with the mode permission before umask.
Example:
if err != nil {
log.Fatal(err)
}
if err := file.Close(); err != nil {
log.Fatal(err)
}
In the example above, we use the OpenFile() method to open a file in Read/Write mode as specified by the os.RDWR() flag. We also specify the os.O_CREATE flag to create the file if it does not exist.
Notice that we also specify the permission of 0755.
If we run the code above, it should create file called new.txt.
-rw-r--r-- 1 csalem 197121 0 Jan 24 15:00 new.txt
Conclusion
This guide taught us how to open and read files in Go using the Open and OpenFile() methods. Explore the documentation to learn more.
Thanks for reading!