How to write integers in a file using Golang?

huangapple go评论72阅读模式
英文:

How to write integers in a file using Golang?

问题

以下是翻译好的内容:

  1. 我生成从0到10的数字
  2. 我创建一个文件
  3. 然后我尝试将整数转换为字符串并写入文件

但是当我打开h.txt文件时,里面没有任何内容

如何修复这个问题并将数字写入h.txt文件?

package main

import "os"

func main() {
    for i := 0; i < 10; i++ { // 生成...
        
        f, _ := os.Create("h.txt") // 创建...
        
        f.WriteString(string(i)) // 写入...
        
        defer f.Close()
    }
}

谢谢!

英文:
  1. I generate numbers from 0 to 10
  2. I create a file
  3. And I try to write to the file by converting integers to string

But when I open the h.txt file there is nothing written

How to fix this and have the numbers written to the h.txt file?

package main

import &quot;os&quot;

func main() {
	for i := 0; i &lt; 10; i++ { // Generating...
		
        f, _ := os.Create(&quot;h.txt&quot;) // creating...
		
        f.WriteString(string(i)) // writing...
		
        defer f.Close()
	}
}

Thanks!

答案1

得分: 6

你的代码存在一些问题。

1)你在循环的每次迭代中都打开文件,os.Create会在文件已存在时截断文件,所以你可能在每次迭代中都在写入和截断文件。

2)你没有检查文件是否正确打开,是否有错误。

3)defer会在函数结束时运行代码,而不是在作用域的末尾运行代码(即迭代的末尾)。

4)你应该正确地转换整数,使用转换并检查错误:_, err := f.WriteString(fmt.Sprintf("%d",i)),然后检查错误。

尝试使用以下代码:

package main

import (
    "fmt"
    "os"
)

func main() {
    f, err := os.Create("h.txt") // 创建文件...
    if err != nil {
        fmt.Printf("创建文件时出错:%v", err)
        return
    }
    defer f.Close()
    for i := 0; i < 10; i++ { // 生成...
        _, err = f.WriteString(fmt.Sprintf("%d\n", i)) // 写入...
        if err != nil {
            fmt.Printf("写入字符串时出错:%v", err)
        }
    }
}
英文:

There are a few issues with your code.

  1. You're opening the file multiple times, every iteration of your loop; os.Create will truncate the file if it already exists, so you may be writing and truncating it on each iteration.

  2. You're not checking that the file opens correctly without error

  3. defer schedules code to run when the function ends, not at the end of the scope. (i.e. at the end of the iteration)

  4. You should convert the integer properly, using a conversion and checking the error: _, err := f.WriteString(fmt.Sprintf(&quot;%d&quot;,i)), and then check the error.

Try this:

package main

import (
    &quot;fmt&quot;
    &quot;os&quot;
)

func main() {
    f, err := os.Create(&quot;h.txt&quot;) // creating...
    if err != nil {
        fmt.Printf(&quot;error creating file: %v&quot;, err)
        return
    }
    defer f.Close()
    for i := 0; i &lt; 10; i++ { // Generating...
        _, err = f.WriteString(fmt.Sprintf(&quot;%d\n&quot;, i)) // writing...
        if err != nil {
            fmt.Printf(&quot;error writing string: %v&quot;, err)
        }
    }
}

huangapple
  • 本文由 发表于 2017年4月25日 10:08:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/43600427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定