how to write a string into a textfile based on console input

agolangf · · 419 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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 ( &#34;bufio&#34; &#34;fmt&#34; &#34;os&#34; &#34;io&#34; ) func main() { scanner := bufio.NewScanner(os.Stdin) file, err := os.Create(&#34;abc.txt&#34;) defer file.Close() if err != nil { fmt.Printf(&#34;Error creating file:%s&#34;, err.Error()) } else { for scanner.Scan() { io.WriteString(file, scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, &#34;Error reading standard input:&#34;, err.Error()) } } } </code></pre> <p>//using bufio</p></pre>msubramm5: <pre><p>Using fmt.Scanf package main</p> <pre><code>import ( &#34;fmt&#34; &#34;os&#34; &#34;io&#34; &#34;strings&#34; ) func main() { file, err := os.Create(&#34;abc.txt&#34;) defer file.Close() if err != nil { fmt.Printf(&#34;Error creating file:%s&#34;, err.Error()) } else { for { var inputStr string fmt.Scanf(&#34;%s&#34;,&amp;inputStr) if strings.EqualFold(inputStr,&#34;quit&#34;){ break } io.WriteString(file,inputStr+&#34;\n&#34;) } } } </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

419 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传