AppDividend
Latest Code Tutorials

How To Open File In Golang | Go File Open Example

0

Golang has an inbuilt package called os, and that package 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 need to import the os package, and then we can use the method.

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

The operating system provides us the interface to the device in the form of a file. Let’s back to open a file.

How to open file in Golang

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

Okay, let’s see how to open file in Golang with example.

Let’s import os package to the main file.

// hello.go

import (
	"os"
)

Now, we can access any method of 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 a 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 file name in this case 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 argument and displays 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, then we will get the error like no such file or directory.

If there is a file, then 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, then 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 now 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 in the fly while opening a file, but for that, we need to change the parameters of os.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 rights if the file is not there, then create one and then open.

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.

FlagMeaning
O_RDONLYIt opens the file read-only
O_WRONLYIt opens the file write-only
O_RDWRIt opens the file read-write
O_APPENDIt appends data to the file when writing
O_CREATEIt creates a new file if none exists
O_EXCLIt is used with O_CREATE, and the file must not exist
O_SYNCIt opens for synchronous I/O
O_TRUNCif possible, truncate file when opened

 

You can use the different flags as 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.

Finally, How To Open File In Golang | Go File Open Example is over.

See also

Golang Strings

Golang I/O Functions

Golang Time

Golang Flag

Leave A Reply

Your email address will not be published.

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