From f4ad92d84bb11b8ffcd7f8b8ec863f94e7625c78 Mon Sep 17 00:00:00 2001 From: hoang Date: Sun, 24 May 2020 10:14:15 +0700 Subject: [PATCH] exercise: read text file line by line --- c1-m4-activity/names.txt | 10 ++++++ c1-m4-activity/read.go | 71 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 c1-m4-activity/names.txt create mode 100644 c1-m4-activity/read.go diff --git a/c1-m4-activity/names.txt b/c1-m4-activity/names.txt new file mode 100644 index 0000000..ba2b472 --- /dev/null +++ b/c1-m4-activity/names.txt @@ -0,0 +1,10 @@ +hoang le +minh tran +nghia nguyen +tuan dang +hung tran +khanh tran +tam do +huu dao +van ly +nam ho \ No newline at end of file diff --git a/c1-m4-activity/read.go b/c1-m4-activity/read.go new file mode 100644 index 0000000..ced4552 --- /dev/null +++ b/c1-m4-activity/read.go @@ -0,0 +1,71 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "os" +) + +const ( + maxLength = 20 +) + +// Name represents data in each line from text +type Name struct { + fname string + lname string +} + +// InitMe init property for Name +func (n *Name) InitMe(fname, lname string) { + n.fname = fname + n.lname = lname + var maxRunes []rune + if len(fname) > maxLength { + maxRunes = []rune(fname) + n.fname = string(maxRunes[:maxLength]) + } + if len(lname) > maxLength { + maxRunes = []rune(lname) + n.lname = string(maxRunes[:maxLength]) + } +} + +/* + successively read each line + create a struct + add each struct to slice + iterate and print slice result +*/ + +func main() { + var fileName string + fmt.Println("Enter name of the file:") + fmt.Scan(&fileName) + file, err := os.Open(fileName) + if err != nil { + log.Fatal(err) + } + defer file.Close() + + names := make([]Name, 0, 5) + if err != nil { + log.Fatal(err) + } + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + text := scanner.Text() + for pos, char := range []byte(text) { + if char == ' ' { + names = append(names, Name{string(text[:pos]), string(text[pos+1:])}) + } + } + } + if err := scanner.Err(); err != nil { + log.Fatal(err) + } + fmt.Printf("names value: %v\n", names) + fmt.Printf("length: %d,capacity: %d \n", len(names), cap(names)) +}