Golang program to check a specified file is exists or not

Here, we are going to learn how to check a specified file is exists or not in Golang (Go Language)?
Submitted by Nidhi, on April 06, 2021

Problem Solution:

In this program, we will check specified file is exist or not using os.Stat() and os.IsNotExist() function and print an appropriate message on the console screen.

Program/Source Code:

The source code to check a specified file exists or not is given below. The given program is compiled and executed successfully.

// Golang program to check a specified file
// exists or not

package main

import "os"
import "fmt"

func main() {
	_, err := os.Stat("Sample.txt")
	if err != nil {
		if os.IsNotExist(err) {
			fmt.Println("Sample.txt file does not exist.")
		}
	} else {
		fmt.Println("Sample.txt exists.")
	}

	_, err1 := os.Stat("Sample1.txt")
	if err1 != nil {
		if os.IsNotExist(err1) {
			fmt.Println("Sample1.txt file does not exist.")
		}
	} else {
		fmt.Println("Sample1.txt exists.")
	}
}

Output:

Sample.txt exists.
Sample1.txt file does not exist.

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt, os packages then we can use a function related to the fmt and os package.

In the main() function, we checked specified file is exists or not with the help of os.Stat() and os.IsNotExist() function and print appropriate messages on the console screen.

In our case, the "Sample.txt" file exists and the "Sample1.txt" file does not exist on the disk.

Golang File Handling Programs »






Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.