<p>Hi I’m a noob at golang and would like to know how you create a golang application that asks for your input you type it in console and it puts in a text file. Thanks </p>
<hr/>**评论:**<br/><br/>qu33ksilver: <pre><p>Take input from console - <a href="https://golang.org/pkg/bufio/#Scanner" rel="nofollow">https://golang.org/pkg/bufio/#Scanner</a></p>
<p>Write to file - <a href="https://golang.org/pkg/io/ioutil/#WriteFile" rel="nofollow">https://golang.org/pkg/io/ioutil/#WriteFile</a></p>
<p>You need to write some plumbing logic to join them together.</p></pre>msubramm5: <pre><pre><code> package main
import (
"bufio"
"fmt"
"os"
"io"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
file, err := os.Create("abc.txt")
defer file.Close()
if err != nil {
fmt.Printf("Error creating file:%s", err.Error())
} else {
for scanner.Scan() {
io.WriteString(file, scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "Error reading standard input:", err.Error())
}
}
}
</code></pre>
<p>//using bufio</p></pre>msubramm5: <pre><p>Using fmt.Scanf
package main</p>
<pre><code>import (
"fmt"
"os"
"io"
"strings"
)
func main() {
file, err := os.Create("abc.txt")
defer file.Close()
if err != nil {
fmt.Printf("Error creating file:%s", err.Error())
} else {
for {
var inputStr string
fmt.Scanf("%s",&inputStr)
if strings.EqualFold(inputStr,"quit"){
break
}
io.WriteString(file,inputStr+"\n")
}
}
}
</code></pre></pre>rogierlommers: <pre><p><a href="https://github.com/genome/log2file" rel="nofollow">https://github.com/genome/log2file</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传