mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 23:08:34 +08:00
@@ -246,7 +246,7 @@ func main () {
|
||||
除了文件句柄,我们还需要 `bufio` 的 `Writer`。我们以只写模式打开文件 `output.dat`,如果文件不存在则自动创建:
|
||||
|
||||
```go
|
||||
outputFile, outputError := os.OpenFile(“output.dat”, os.O_WRONLY|os.O_CREATE, 0666)
|
||||
outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666)
|
||||
```
|
||||
|
||||
可以看到,`OpenFile` 函数有三个参数:文件名、一个或多个标志(使用逻辑运算符“|”连接),使用的文件权限。
|
||||
@@ -270,7 +270,7 @@ outputWriter := bufio.NewWriter(outputFile)
|
||||
|
||||
缓冲区的内容紧接着被完全写入文件:`outputWriter.Flush()`
|
||||
|
||||
如果写入的东西很简单,我们可以使用 `fmt.Fprintf(outputFile, “Some test data.\n”)` 直接将内容写入文件。`fmt` 包里的 F 开头的 Print 函数可以直接写入任何 `io.Writer`,包括文件(请参考[章节12.8](12.8.md)).
|
||||
如果写入的东西很简单,我们可以使用 `fmt.Fprintf(outputFile, "Some test data.\n")` 直接将内容写入文件。`fmt` 包里的 F 开头的 Print 函数可以直接写入任何 `io.Writer`,包括文件(请参考[章节12.8](12.8.md))。
|
||||
|
||||
程序 `filewrite.go` 展示了不使用 `fmt.FPrintf` 函数,使用其他函数如何写文件:
|
||||
|
||||
@@ -283,15 +283,15 @@ import "os"
|
||||
|
||||
func main() {
|
||||
os.Stdout.WriteString("hello, world\n")
|
||||
f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0)
|
||||
f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0666)
|
||||
defer f.Close()
|
||||
f.WriteString("hello, world in a file\n")
|
||||
}
|
||||
```
|
||||
|
||||
使用 `os.Stdout.WriteString(“hello, world\n”)`,我们可以输出到屏幕。
|
||||
使用 `os.Stdout.WriteString("hello, world\n")`,我们可以输出到屏幕。
|
||||
|
||||
我们以只写模式创建或打开文件“test”,并且忽略了可能发生的错误:`f, _ := os.OpenFile(“test”, os.O_CREATE|os.O_WRONLY, 0)`
|
||||
我们以只写模式创建或打开文件"test",并且忽略了可能发生的错误:`f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0666)`
|
||||
|
||||
我们不使用缓冲区,直接将内容写入文件:`f.WriteString( )`
|
||||
|
||||
|
Reference in New Issue
Block a user