Home »
Golang »
Golang Programs
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 [Last updated : March 04, 2023]
Checking a file is exists or not in Golang
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 code to check a specified file is exists or not
// 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 »