Open In App

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.

Syntax:



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

Example 1:




// 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()
}

Output:



Example 2:




// 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()
}

Output:


Article Tags :