Go Program to Check if a File Exists

Introduction

Checking if a file exists is a common task in file handling. In Go, you can check if a file exists by attempting to open the file and handling the error appropriately. This guide will demonstrate how to write a Go program that checks whether a file exists.

Problem Statement

Create a Go program that:

  • Takes a filename as input.
  • Checks if the file exists.
  • Displays a message indicating whether the file exists or not.

Example:

  • Input: "example.txt"
  • Output:
    File exists.
    

    or

    File does not exist.
    

Solution Steps

  1. Import the Necessary Packages: Use import "fmt" and import "os" for file operations and formatted I/O.
  2. Write a Function to Check if the File Exists: Implement a function that tries to open the file and checks for specific errors.
  3. Write the Main Function: Define the main function, which is the entry point of every Go program.
  4. Prompt the User to Enter a Filename: Use fmt.Scanln or fmt.Scanf to take the filename as input.
  5. Call the Function to Check if the File Exists: Use the function to determine whether the specified file exists.
  6. Display the Result: Use fmt.Println to display whether the file exists or not.

Go Program

package main

import (
    "fmt"
    "os"
)

// Step 2: Implement a function to check if the file exists
func fileExists(filename string) bool {
    _, err := os.Stat(filename)
    if os.IsNotExist(err) {
        return false
    }
    return err == nil
}

/**
 * Go Program to Check if a File Exists
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 4: Prompt the user to enter a filename
    var filename string
    fmt.Print("Enter the filename: ")
    fmt.Scanln(&filename)

    // Step 5: Call the function to check if the file exists
    if fileExists(filename) {
        fmt.Println("File exists.")
    } else {
        fmt.Println("File does not exist.")
    }
}

Explanation

Step 2: Implement a Function to Check if the File Exists

  • The fileExists function uses the os.Stat function to retrieve file information.
    • os.Stat returns an error if the file does not exist or if there is another issue accessing it.
    • The function checks if the error returned is os.IsNotExist(err), which specifically indicates that the file does not exist.
    • If no error is returned, or if the error is not related to the file’s existence, the function returns true to indicate that the file exists.

Step 3: Write the Main Function

  • The main function is the entry point of the program. It prompts the user for a filename and calls the fileExists function.

Step 4: Prompt the User to Enter a Filename

  • The program prompts the user to enter the filename using fmt.Print and reads the input using fmt.Scanln.

Step 5: Call the Function to Check if the File Exists

  • The program checks whether the file exists by calling the fileExists function with the provided filename.

Step 6: Display the Result

  • The program prints a message indicating whether the file exists or not using fmt.Println.

Output Example

Example 1:

Enter the filename: example.txt
File exists.

Example 2:

Enter the filename: nonexistentfile.txt
File does not exist.

Example 3 (Empty input):

Enter the filename: 
File does not exist.

Conclusion

This Go program demonstrates how to check if a file exists using the os package. It covers basic file operations such as checking for file existence and handling errors in Go. This example is useful for beginners learning Go programming and understanding how to perform basic file handling operations.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top