AppDividend
Latest Code Tutorials

How To Create File In Golang | os.Create() Function

1

Golang has the inbuilt package called os, and that package has a function called Create() that can be used to create a file. File create, read, and write the basic operations in Go. We can create a file using the os.Create() function. First, we need to import os package, and then we can use its method. The operating system provides us the interface to the device in the create and open the file.

Create File In Golang

Let’s create an empty file in Go first. For that, import os module.

Write the following code inside the hello.go file.

// hello.go

package main

import (
	"log"
	"os"
)

func main() {
	emptyFile, err := os.Create("emptyFile.txt")
	if err != nil {
		log.Fatal(err)
	}
	log.Println(emptyFile)
	emptyFile.Close()
}

In the above code, we have imported log and os packages.

Then inside the main() function, we have used os.Create() function and pass the filename that we want to create. If the error occurs, then it will log, and the program will be stopped else it will log the new empty file.

You can find the emptyFile.txt file in the same directory as hello.go.

func Create()

See the following syntax.

func Create(name string) (*File, error)

The Create() function is an inbuilt function that creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it will be created with mode 0666 (before umask).

If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

If we rerun the above code, then it truncates the existing file. This function returns a File descriptor

You can open the file using os.Open() function.

Conclusion

In golang, use the os package and use the os.Create() function to create a file. We can open the file using os.Open() function. We are also using defer to close the file access once the function has finished running (which is an elegant way of remembering to close files).

1 Comment
  1. Germán Lugo says

    Hi, thank you for the snipped.
    Can you create the emptyFile.txt file in a diferent directory as hello.go?

    Thank you for your help.

Leave A Reply

Your email address will not be published.

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