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