Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Create an empty file in Go (Golang)

Posted on February 21, 2020February 21, 2020 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
  • Follow @golangbyexample

    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

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme