golang

Golang OS Open

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:

import "os"

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:

mkdir read_file

Navigate into the directory and create a text file:

cd read_file
touch hello.txt

Once we have a text file to read, open it with your favorite text editor and add some content:

$ vim hello.txt
"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:

file, err := os.Open("hello.txt")
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:

file_data := make([]byte, 50)
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:

file, err := os.Open("info.txt")

Error Output:

open info.txt: The system cannot find the file specified.
exit status 1

os.OpenFile()

The OpenFile() method allows you to open a file with the specified flag. Such flags include:

  1. O_RDONLY– Read-Only Mode.
  2. O_WRONLY. Opens file in Write Only mode.
  3. O_RDWR–Open the file in Read-Write mode.
  4. O_APPEND–Appends data to the file when writing.
  5. O_TRUNC–Truncate the file when opened, where applicable.
  6. O_SYNC – Open the file for synchronous I/O.
  7. 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:

file, err := os.OpenFile("new.txt", os.O_RDWR|os.O_CREATE, 0777)
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.

$ ls -la
-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!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list