-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
exercise: read text file line by line
- Loading branch information
Showing
2 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
} |