3 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
如何移動(dòng)到循環(huán)之前的下一個(gè)標(biāo)記
scanner := bufio.NewScanner(file)
scanner.Scan() // this moves to the next token
for scanner.Scan() {
fmt.Println(scanner.Text())
}
文件
1
2
3
輸出
2
3
https://play.golang.org/p/I2w50zFdcg0

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
例如,
package main
import (
"bufio"
"fmt"
"os"
)
func readFile(filename string) (int, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
defer f.Close()
count := 0
s := bufio.NewScanner(f)
if s.Scan() {
for s.Scan() {
count++
}
}
if err := s.Err(); err != nil {
return 0, err
}
return count, nil
}
func main() {
filename := `test.file`
count, err := readFile(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Println(count)
}
輸出:
$ cat test.file
1234567890
abc
$ go run count.go
1
$

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
你可以嘗試這樣的事情
func readFile(fileLocation string) int {
fileOpen, _ := os.Open(fileLocation)
defer fileOpen.Close()
fileScanner := bufio.NewScanner(fileOpen)
counter := 0
for fileScanner.Scan() {
// read first line and ignore
fileScanner.Text()
break
}
for fileScanner.Scan() {
// read remaining lines and process
txt := fileScanner.Text()
counter = counter + 1
// do something with text
return counter
}
編輯:
func readFile(fileLocation string) int {
fileOpen, _ := os.Open(fileLocation)
defer fileOpen.Close()
fileScanner := bufio.NewScanner(fileOpen)
counter := 0
if fileScanner.Scan() {
// read first line and ignore
fileScanner.Text()
}
for fileScanner.Scan() {
// read remaining lines and process
txt := fileScanner.Text()
// do something with text
counter = counter + 1
}
return counter
}
- 3 回答
- 0 關(guān)注
- 195 瀏覽
添加回答
舉報(bào)