Go Program to Read a File Line by Line

Introduction

Reading a file line by line is a common task in many applications, especially when processing text files. In Go, you can achieve this by using the bufio package, which provides a buffered reader to efficiently read text. This guide will demonstrate how to write a Go program that reads a file line by line.

Problem Statement

Create a Go program that:

  • Takes a filename as input.
  • Reads the file line by line.
  • Displays each line on the console.

Example:

  • Input: Filename "example.txt" with contents:
    Hello, World!
    Welcome to Go programming.
    Reading file line by line.
    
  • Output:
    Line 1: Hello, World!
    Line 2: Welcome to Go programming.
    Line 3: Reading file line by line.
    

Solution Steps

  1. Import the Necessary Packages: Use import "fmt", import "os", and import "bufio" for file operations and buffered I/O.
  2. Write a Function to Read the File Line by Line: Implement a function that opens the file and reads it line by line using a buffered reader.
  3. Write the Main Function: Define the main function, which is the entry point of every Go program.
  4. Prompt the User to Enter the Filename: Use fmt.Scanln or fmt.Scanf to take the filename as input.
  5. Call the Function to Read the File Line by Line: Use the function to read the file and display each line.
  6. Handle Errors: Ensure that any errors encountered while opening or reading the file are properly handled.

Go Program

package main

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

// Step 2: Implement a function to read the file line by line
func readFileLineByLine(filename string) error {
    // Open the file
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    // Create a new scanner to read the file line by line
    scanner := bufio.NewScanner(file)
    lineNumber := 1
    for scanner.Scan() {
        fmt.Printf("Line %d: %s\n", lineNumber, scanner.Text())
        lineNumber++
    }

    // Check for errors during the scanning process
    if err := scanner.Err(); err != nil {
        return err
    }

    return nil
}

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

    // Step 5: Call the function to read the file line by line
    err := readFileLineByLine(filename)
    if err != nil {
        fmt.Println("Error reading file:", err)
    }
}

Explanation

Step 2: Implement a Function to Read the File Line by Line

  • The readFileLineByLine function performs the following steps:
    • It opens the file using os.Open. If the file cannot be opened, it returns an error.
    • It creates a new bufio.Scanner to read the file line by line.
    • It iterates over each line in the file using scanner.Scan(), printing each line with its line number.
    • After reading all lines, it checks for any errors that may have occurred during scanning using scanner.Err().

Step 3: Write the Main Function

  • The main function prompts the user for a filename and calls readFileLineByLine to read the file.

Step 4: Prompt the User to Enter the 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 Read the File Line by Line

  • The program calls readFileLineByLine with the provided filename to read the file line by line.

Step 6: Handle Errors

  • The program checks for errors when opening and reading the file. If an error occurs, it prints an error message using fmt.Println.

Output Example

Example 1:

If example.txt contains:

Hello, World!
Welcome to Go programming.
Reading file line by line.

The program will output:

Enter the filename: example.txt
Line 1: Hello, World!
Line 2: Welcome to Go programming.
Line 3: Reading file line by line.

Example 2:

If the file does not exist:

Enter the filename: nonexistentfile.txt
Error reading file: open nonexistentfile.txt: no such file or directory

Conclusion

This Go program demonstrates how to read a file line by line using the bufio package. It covers basic file operations such as opening, reading, and handling errors in Go. This example is useful for beginners learning Go programming and understanding how to process text files efficiently.

Leave a Comment

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

Scroll to Top