Files
the-way-to-go_ZH_CN/eBook/12.5.md
Haigang Zhou d29644465a 第十二章修改 (#838)
Co-authored-by: Joe Chen <jc@unknwon.io>
2022-05-12 21:59:20 +08:00

59 lines
1.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 12.5 用 buffer 读取文件
在下面的例子中,我们结合使用了缓冲读取文件和命令行 flag 解析这两项技术。如果不加参数,那么你输入什么屏幕就打印什么。
参数被认为是文件名,如果文件存在的话就打印文件内容到屏幕。命令行执行 `cat test` 测试输出。
示例 12.11 [cat.go](examples/chapter_12/cat.go)
```go
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func cat(r *bufio.Reader) {
for {
buf, err := r.ReadBytes('\n')
fmt.Fprintf(os.Stdout, "%s", buf)
if err == io.EOF {
break
}
}
return
}
func main() {
flag.Parse()
if flag.NArg() == 0 {
cat(bufio.NewReader(os.Stdin))
}
for i := 0; i < flag.NArg(); i++ {
f, err := os.Open(flag.Arg(i))
if err != nil {
fmt.Fprintf(os.Stderr, "%s:error reading from %s: %s\n", os.Args[0], flag.Arg(i), err.Error())
continue
}
cat(bufio.NewReader(f))
f.Close()
}
}
```
在 [12.6 章节](12.6.md),我们将看到如何使用缓冲写入。
**练习 12.6**[cat_numbered.go](exercises/chapter_12/cat_numbered.go)
扩展 [cat.go](exercises/chapter_12/cat.go) 例子,使用 flag 添加一个选项,目的是为每一行头部加入一个行号。使用 `cat -n test` 测试输出。
## 链接
- [目录](directory.md)
- 上一节:[从命令行读取参数](12.4.md)
- 下一节:[用切片读写文件](12.6.md)