【发布时间】:2017-07-23 21:23:03
【问题描述】:
我正在尝试读取所有标准输入并将其写入文件。它没有向提供的文件写入任何内容。为什么它不起作用?
package main
import (
"os"
"bytes"
"fmt"
"bufio"
)
func main() {
fn := os.Args[1]
var input bytes.Buffer
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Fprintf(&input, scanner.Text())
fmt.Fprintf(&input, "\n")
}
fi, _ := os.Open(fn)
defer fi.Close()
fi.Write(input.Bytes())
}
然后……
touch writetothis.txt
echo "input text" | go run main.go writetothis.txt
# writetothis.txt is empty
【问题讨论】:
-
你没有检查
fi, _ := os.Open(fn)线上的错误你怎么知道它甚至打开了..它可能会默默地失败。