Q:

Golang program to check a specified file is exists or not

belongs to collection: Golang File Handling Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 fmtos 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to set file permission... >>
<< Golang program to open a file in append mode...