How to check if a file is empty in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To check check if a file is empty or not golang os.stat().st_size method just pass you filename with path in os.stat().st_size method it will return file size if size is 0 means file is empty else file is not empty.

Today, I’m going to show how do i check if a file is empty in golang, as above mentioned I’m going to use the os.stat() method to check the file is blank or not.

Let’s start today’s tutorial how to check if a file is empty in golang?

let’s write a code.

package main

import (
  "os"
  "fmt"
)

func main() {
	check_file = os.stat("sample.txt").st_size

	if(check_file == 0):
  		print("The file is empty.")
	else:
	    print("The file is not empty.")
}

The os.stat() method provide details about statistics of file and here using st_size we are trying to get file size. let’s see on output which file empty or which not.

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts