Golang

 

 

In this tutorial, we will create a basic text editor in Go programming language. This editor will allow the user to open, edit, and save text files. The goal of this project is to demonstrate how to work with files, create a simple user interface, and perform basic text editing operations in Go.

Objective

The objective of this project is to create a lightweight text editor that can open and save files. It will help you understand basic file handling in Go and introduce simple user input handling. By the end of this project, you will be able to expand the editor with additional features such as cut, copy, paste, or even text formatting.

Code: Simple Text Editor in Go

Here is the code to create a basic text editor in Go. It uses the “fmt” and “os” packages for file handling and basic input/output operations:


    package main

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

    // Function to open a file and display its content
    func openFile(filePath string) (string, error) {
        file, err := os.Open(filePath)
        if err != nil {
            return "", err
        }
        defer file.Close()

        var content strings.Builder
        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
            content.WriteString(scanner.Text() + "\n")
        }
        if err := scanner.Err(); err != nil {
            return "", err
        }

        return content.String(), nil
    }

    // Function to save content to a file
    func saveFile(filePath string, content string) error {
        file, err := os.Create(filePath)
        if err != nil {
            return err
        }
        defer file.Close()

        _, err = file.WriteString(content)
        return err
    }

    func main() {
        fmt.Println("Welcome to Go Text Editor")

        // Prompt the user for file operations
        fmt.Print("Enter the file path to open: ")
        var filePath string
        fmt.Scanln(&filePath)

        content, err := openFile(filePath)
        if err != nil {
            fmt.Println("Error opening file:", err)
            return
        }

        fmt.Println("\nCurrent File Content:")
        fmt.Println(content)

        // Get user input for editing the file
        fmt.Print("\nEnter new content to add to the file (type 'exit' to stop):\n")
        scanner := bufio.NewScanner(os.Stdin)
        var newContent string

        for {
            scanner.Scan()
            line := scanner.Text()
            if line == "exit" {
                break
            }
            newContent += line + "\n"
        }

        // Combine original content with new input
        updatedContent := content + newContent

        // Save the updated content to the file
        err = saveFile(filePath, updatedContent)
        if err != nil {
            fmt.Println("Error saving file:", err)
        } else {
            fmt.Println("File saved successfully!")
        }
    }
    

Explanation of the Program Structure

This Go program contains several important components:

  • openFile function: Opens the file specified by the user, reads its content, and returns it as a string.
  • saveFile function: Saves the new content into the specified file by overwriting the existing content.
  • main function: The entry point of the program. It prompts the user to input the file path, displays the file content, accepts new content from the user, and saves it back to the file.

How to Run the Program

To run the program, follow these steps:

  1. Ensure you have Go installed on your computer. If not, download it from the official Go website.
  2. Save the provided code in a file called text_editor.go.
  3. Open a terminal or command prompt and navigate to the directory where you saved text_editor.go.
  4. Run the following command to execute the program: go run text_editor.go.
  5. Follow the prompts in the terminal to open a text file, edit its content, and save it back.
© 2025 Learn Programming. All rights reserved.

 

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 :)