Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Create an empty file in Go (Golang)

Posted on February 21, 2023February 21, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

os.Create() can be used to create an empty file in go. The signature of the function is

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

Basically this function

  • Create a named file with mode 0666
  • It truncates the file if it already exits
  • In case of path issue, it returns a Path error
  • It returns a file descriptor which can be used for both reading and write

Code:

package main
import (
"log"
"os"
)
func main() {
file, err := os.Create("emptyFile.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
}

Output:

Check the contents of the file. It will be empty
  • empty
  • file
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP