Skip to content

Commit

Permalink
exercise: read text file line by line
Browse files Browse the repository at this point in the history
  • Loading branch information
hoangbits committed May 24, 2020
1 parent 1a27ab7 commit f4ad92d
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
10 changes: 10 additions & 0 deletions c1-m4-activity/names.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
hoang le
minh tran
nghia nguyen
tuan dang
hung tran
khanh tran
tam do
huu dao
van ly
nam ho
71 changes: 71 additions & 0 deletions c1-m4-activity/read.go
Original file line number Diff line number Diff line change
@@ -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))
}

0 comments on commit f4ad92d

Please sign in to comment.