Go is a universal programming language. It provides the ability to create files using the Create() function from the os package. Let us learn how to accomplish this.

Golang Create

The syntax of the function is as shown:

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

The function takes the filename as the argument. It then creates a file with the specified name or an error.

The following are important points to not about the Create() function

  1. The function creates a file with mode 066.
  2. If the provided path to the file is invalid, the method returns a PathError error.
  3. The function returns a file descriptor which we can use for reading or writing to the file.

Since the method is defined in the os package, we need to import it before use.

We can do this:

Consider the example below that creates a file in the current working directory:

package main


import (


    “fmt”


    “log”


    “os”

)

func main() {


    file, err := os.Create(“newfile.”)


    if err != nil {


        log.Fatal(err)


    }


    fmt.Println(“File created successfully”)


    defer file.Close()

}

The above program will create a file in the current working directory with the name specified in the Create() method.

You can also provide an absolute path to the Create() function. An example is as shown:

package main


import (


    “fmt”


    “log”


    “os”


    “path/filepath”

)


func main() {


    path := filepath.Join(“home”, “ubuntu”, “workspace”, “newfile.txt”)


    fmt.Println(path)


    file, err := os.Create(path)


    if err != nil {


        log.Fatal(err)


    }


    fmt.Println(“File created successfully”)


    defer file.Close()

}

In the program above, we use the filepath.Join() method to create an absolute path to the file, which we then provide to the Create() method.

The resulting path is as:

home/ubuntu/workspace/newfile.txt

Note the file will be created only if the path specified exists.

Otherwise, the compiler will return an error as:

…: The system cannot find the path specified.

exit status 1

Conclusion

This article taught us how to create a file using the Create() method in the os package.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352ac5b03e.jpg" height="112" src="data:image/svg xml,” width=”112″>

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