Golang Create
The syntax of the function is as shown:
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
- The function creates a file with mode 066.
- If the provided path to the file is invalid, the method returns a PathError error.
- 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:
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:
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:
Note the file will be created only if the path specified exists.
Otherwise, the compiler will return an error as:
exit status 1
Conclusion
This article taught us how to create a file using the Create() method in the os package.