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
- Import the Necessary Packages: Use
import "fmt",import "os", andimport "bufio"for file operations and buffered I/O. - 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.
- Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Prompt the User to Enter the Filename: Use
fmt.Scanlnorfmt.Scanfto take the filename as input. - Call the Function to Read the File Line by Line: Use the function to read the file and display each line.
- 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
readFileLineByLinefunction 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.Scannerto 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().
- It opens the file using
Step 3: Write the Main Function
- The
mainfunction prompts the user for a filename and callsreadFileLineByLineto read the file.
Step 4: Prompt the User to Enter the Filename
- The program prompts the user to enter the filename using
fmt.Printand reads the input usingfmt.Scanln.
Step 5: Call the Function to Read the File Line by Line
- The program calls
readFileLineByLinewith 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.