• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer

GitopsCentral

  • Home
  • Courses
  • Roadmap
  • About
  • Log In
  • Sign Up

Read File: Go lang

May 10, 2019 by shaik zillani

© clipartmax.com

In this blog post, I will show you how to read a file in golang using bufio. Create a file with name test.txt and add the below contents,

ken thompson
alan donovan
brian kernighan

File Read Example

package main

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

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {

	type Name struct {
	  firstname string
	  lastname string
	}

	fmt.Print("Please enter file name: ")
	in := bufio.NewReader(os.Stdin)
	line,_ := in.ReadString('\n')
	filename := strings.TrimSuffix(line,"\n")

	s := make([]Name,0)

	file, err := os.Open(filename)
	
	check(err)
    
    defer file.Close()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {
        line := scanner.Text()
        splitLine := strings.Split(string(line), " ")

		nameStruct := Name {firstname: splitLine[0], lastname: splitLine[1]}
		s = append(s,nameStruct)
    }

    fmt.Println("File context read via slice of Structs: ")

      for i := 0; i < len(s); i++ {
        fmt.Printf("%s\n", s[i])
       }

}

This will read the file and the contents line by line and stores then in slice of struct then reads and prints them by delimiting each line with a space.

Output

Please enter file name: test.txt

---------------------
FirstName | LastName
---------------------
ken thompson
alan donovan
brian kernighan

golang golang

Primary Sidebar

en English
ar Arabiczh-CN Chinese (Simplified)nl Dutchen Englishfr Frenchde Germanhi Hindiid Indonesianit Italianja Japanesems Malaypt Portugueseru Russianes Spanishte Telugu

Course Tags

concurrency free go golang

Recent Posts

  • Roadmap to Mastery
  • Increase SSH connection timeout
  • Check Certificate expiry in Kubernetes
  • space invaders in golang
  • creating kubernetes cluster using eksctl
  • Facebook
  • GitHub
  • YouTube

Contact

Navigation

  • goacademy pro

Footer

  • Facebook
  • GitHub
  • Instagram
  • LinkedIn
  • Twitter

info@gitopscentral.com


+91 8341443220

© Copyright 2016-2024 gitopscentral · All Rights Reserved ·