Files
the-way-to-go_ZH_CN/eBook/18.7.md
songleo 830785f46e modified: eBook/18.10.md
modified:   eBook/18.3.md
	modified:   eBook/18.4.md
	modified:   eBook/18.5.md
	modified:   eBook/18.6.md
	modified:   eBook/18.7.md
	modified:   eBook/18.8.md
	modified:   eBook/18.9.md
2016-01-03 22:25:47 +08:00

52 lines
1.2 KiB
Markdown
Raw 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.

# 18.7 文件
1如何打开一个文件并读取
```go
file, err := os.Open("input.dat")
if err != nil {
fmt.Printf("An error occurred on opening the inputfile\n" +
"Does the file exist?\n" +
"Have you got acces to it?\n")
return
}
defer file.Close()
iReader := bufio.NewReader(file)
for {
str, err := iReader.ReadString('\n')
if err != nil {
return // error or EOF
}
fmt.Printf("The input was: %s", str)
}
```
2如何通过切片读写文件
```go
func cat(f *file.File) {
const NBUF = 512
var buf [NBUF]byte
for {
switch nr, er := f.Read(buf[:]); true {
case nr < 0:
fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n",
f.String(), er.String())
os.Exit(1)
case nr == 0: // EOF
return
case nr > 0:
if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr {
fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n",
f.String(), ew.String())
}
}
}
}
```
## 链接
- [目录](directory.md)
- 上一节:[函数](18.6.md)
- 下一节:[协程goroutine与通道channel](18.8.md)