Introduction: In this tutorial, we will explore how to read the contents of a file and display them in the console using the Go programming language. Reading files is one of the basic and essential operations that every developer needs to master, especially when working with data files. This task will teach us how to work with file I/O (input/output) operations in Go.

Objective: The objective of this program is to:

  • Open an existing file for reading.
  • Read the contents of the file.
  • Display the contents to the console.

Go Program Code


package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    // Specify the file name to read from
    fileName := "example.txt"

    // Open the file
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    // Create a scanner to read the file line by line
    scanner := bufio.NewScanner(file)
    
    // Read each line from the file and print it
    fmt.Println("Contents of the file:")
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    // Check if there was an error reading the file
    if err := scanner.Err(); err != nil {
        fmt.Println("Error reading file:", err)
    }
}
        

Program Explanation

The program above reads the contents of a file and prints each line on the console.

Code Breakdown:

  • import: We import three necessary packages:
    • bufio: To create a scanner that reads the file line by line.
    • fmt: For printing output to the console.
    • os: To open and handle the file operations.
  • fileName: This variable holds the name of the file we want to read. In this case, it’s “example.txt”.
  • os.Open(fileName): This function is used to open the file. If an error occurs (like if the file does not exist), it prints the error message and terminates the program.
  • defer file.Close(): This ensures that the file is closed when the program finishes execution, even if an error occurs.
  • bufio.NewScanner(file): This scanner allows us to read the file line by line, making it easy to process large files.
  • scanner.Scan(): This method reads the next line of the file. The loop continues as long as there are lines to read.
  • scanner.Text(): This method retrieves the text of the current line, which is then printed to the console.
  • scanner.Err(): This checks for any errors that might have occurred during reading the file.

How to Run the Program

    1. Make sure you have Go installed on your system. You can download Go from the official website: Go Downloads.
    2. Create a new text file (e.g., example.txt) and add some content to it. Place this file in the same directory as your Go program.
    3. Write the Go program provided above in a file, say readfile.go.
    4. Open a terminal/command prompt, navigate to the directory where your Go program is located, and run the following command to execute the program:
go run readfile.go
  1. The program will open the example.txt file, read its contents, and display them on the console.
© 2024 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)