How to Create an Empty File in Golang?
Last Updated :
02 Apr, 2020
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:
package main
import (
"log"
"os"
)
func main() {
myfile, e := os.Create( "GeeksforGeeks.txt" )
if e != nil {
log.Fatal(e)
}
log.Println(myfile)
myfile.Close()
}
|
Output:
Example 2:
package main
import (
"log"
"os"
)
func main() {
myfile, e := os.Create( "/Users/anki/Documents/new_folder/GeeksforGeeks.txt" )
if e != nil {
log.Fatal(e)
}
log.Println(myfile)
myfile.Close()
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...