Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Touch a file in Go (Golang)

Posted on January 16, 2023February 23, 2023 by admin

Touching a file means

  • Create an empty file if the file doesn’t already exist
  • If the file already exists then update the modified time of the file.
package main
import (
"fmt"
"log"
"os"
"time"
)
func main() {
fileName := "temp.txt"
_, err := os.Stat(fileName)
if os.IsNotExist(err) {
file, err := os.Create("temp.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
} else {
currentTime := time.Now().Local()
err = os.Chtimes(fileName, currentTime, currentTime)
if err != nil {
fmt.Println(err)
}
}
}

Output:

When running the first time it will create the file. After the first time, it will update the modified time of the file.

  • 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