Golang File Open: How to Open File in Golang

0
7342
How To Open File In Golang | Go File Open Example

Golang has a built-in package called os, which has a function called OpenFile() that can be used to open a file. We can open a file using the os.OpenFile() function. First, we must import the os package and then use the method.

The reader and writer interfaces in Golang are similar abstractions. We read and write bytes without understanding where or how the reader gets its data or where the writer is sending the data. 

One of the fundamental aspects of UNIX is that everything is a file. However, we don’t know what the operating system’s device drivers abstract the file descriptor maps.

The operating system provides the interface to the device in the form of a file. So let’s get back to opening a file.

How to open a file in Golang

To open a file in Golang, use the os.OpenFile() function.  The os.Open() is a built-in Go function that takes a filepath, flag, and file mode as arguments and opens and reads the file.

Let’s import the os package to the main file.

// hello.go

import (
	"os"
)

Now, we can access any method of the os package.

Create a file in the same folder as your main file(hello.go) called app.txt.

We will open the app.txt file in this program.

You can also write the following line content inside the app.txt file.

hello baby Yoda

So, we now have our example file called app.txt.

os.OpenFile(name/path string, flag int, perm FileMode)

OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with the specified flag (O_RDONLY, etc.).

The first parameter is a file name, which is the complete file path of that file.

If the file does not exist, and the O_CREATE flag is passed, it is created with mode perm (before umask). If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

See the complete example of how to open a file in Go. Write the following code inside the hello.go file.

// hello.go

package main

import (
	"fmt"
	"os"
)

var path = "app.txt"

func isError(err error) bool {
	if err != nil {
		fmt.Println(err.Error())
	}
	return (err != nil)
}

func main() {
	fmt.Println("Opening a file ")
	var file, err = os.OpenFile(path, os.O_RDWR, 0644)
	if isError(err) {
		return
	}
	defer file.Close()
}

We have defined a file path or name called app.txt because it is the same directory.

We have defined two functions.

  1. isError()
  2. main()

The isError() function takes an error as an argument and displays it on the console if, during the file, we encounter any error.

Inside the main() function, we are using os.OpenFile() function and pass three parameters.

  1. filename
  2. flag
  3. file permission

If the file is not there, we will get the error like no such file or directory.

If there is a file, it will open, and then we can read and write to that file.

Run the hello.go file, and if you don’t see any error, we have successfully opened a file.

Output

➜  hello go run hello.go
Opening a file
➜  hello

Okay, now change the filename to, let’s say, appss.txt and run the above program.

// hello.go

package main

import (
	"fmt"
	"os"
)

var path = "appss.txt"

func isError(err error) bool {
	if err != nil {
		fmt.Println(err.Error())
	}
	return (err != nil)
}

func main() {
	fmt.Println("Opening a file ")
	var file, err = os.OpenFile(path, os.O_RDWR, 0644)
	if isError(err) {
		return
	}
	defer file.Close()
}

Output

➜  hello go run hello.go
Opening a file
open appss.txt: no such file or directory
➜  hello

We can solve this problem and create a file on the fly while opening a file, but we need to change the os parameters.OpenFile() function. We need to change file permission and flag.

See the following code.

// hello.go

package main

import (
	"fmt"
	"os"
)

var path = "appss.txt"

func isError(err error) bool {
	if err != nil {
		fmt.Println(err.Error())
	}
	return (err != nil)
}

func main() {
	fmt.Println("Opening a file ")
	var file, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)
	if isError(err) {
		return
	}
	defer file.Close()
}

See the os.OpenFile() function closely.

var file, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)

We have given the right if the file is not there, create one and then open it.

Output

➜  hello go run hello.go
Opening a file
➜  hello

OS Package OpenFile Flags

The Golang OS package OpenFile function opens files using flags and permissions. One of the first three flags below must be provided in the OpenFile function.

Flag Meaning
O_RDONLY It opens the file read-only
O_WRONLY It opens the file write-only
O_RDWR It opens the file read-write
O_APPEND It appends data to the file when writing
O_CREATE It creates a new file if none exists
O_EXCL It is used with O_CREATE, and the file must not exist
O_SYNC It opens for synchronous I/O
O_TRUNC if possible, truncate the file when opened

 

You can use the different flags per your requirement while opening a file.

Conclusion

In golang, the os package deals with creating and opening a file.

You can find more on the Golang os package.

That’s it.

Related posts

Golang os.Create()

Golang os.Remove()

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.