How to Create an Empty File in Golang?

Like other programming languages, Go language also allows you to create files. For creating a file it provides Create() function, this function is used to create or truncates the given named file.

  • This method will truncate the file, if the given file is already exists.
  • This method will create a file with mode 0666, if the given file doesn’t exist.
  • If the given path is not correct, then this method will throw an error of type *PathError.
  • This method return a file descriptor which can be used for both reading and write.
  • It is defined under the os package so, you have to import os package in your program for accessing Create() function.

Syntax:

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate how to create
// an empty file in the default directory
package main
  
import (
    "log"
    "os"
)
  
func main() {
  
    // Creating an empty file
    // Using Create() function
    myfile, e := os.Create("GeeksforGeeks.txt")
    if e != nil {
        log.Fatal(e)
    }
    log.Println(myfile)
    myfile.Close()
}

chevron_right


Output:

creating an empty file in golang



Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate how to create
// an empty file in the new directory
package main
  
import (
    "log"
    "os"
)
  
func main() {
  
    // Creating an empty file
    // Using Create() function
    myfile, e := os.Create("/Users/anki/Documents/new_folder/GeeksforGeeks.txt")
    if e != nil {
        log.Fatal(e)
    }
    log.Println(myfile)
    myfile.Close()
}

chevron_right


Output:

creating an empty file in golang in specified directory




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.