无法写入文件

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

Go: Not able to write to a file

问题

文件的权限:-rw-r--r--

我将权限更改为-rw-rw--rw--,但它仍然无法工作。我想了解为什么这段代码不起作用:

该函数创建一个文件,但函数没有向文件中写入任何内容。我也没有收到任何错误信息。

newfileCreate, err := os.Create("brainnew.txt")
newfile, err := os.Open(newfileCreate.Name())
	if err != nil {
		log.Fatal(err)
	}
defer newfile.Close()
newfile.WriteString("sdsds sds")

// 我尝试写入字节,但也不起作用!

但是,如果我尝试这段代码,它可以工作!

str := "example-text"
data := []byte(str)
ioutil.WriteFile("data.txt", data, 0644)
英文:

Permission of file: -rw-r--r--

I changed the permissions to -rw-rw--rw-- but it still doesn't work. I want to understand why this code is not working:

The function creates a file. But the function does not write anything to the file. I also don't get any error.

newfileCreate, err := os.Create("brainnew.txt")
newfile, err := os.Open(newfileCreate.Name())
	if err != nil {
		log.Fatal(err)
	}
defer newfile.Close()
newfile.WriteString("sdsds sds")

// I tried writing bytes but it that also doesn't work!

But, if I try this code, it works!

str := "example-text"
data := []byte(str)
ioutil.WriteFile("data.txt", data, 0644)

答案1

得分: 0

问题出在os.Open函数上。如果你查看该函数的文档,会发现以下内容:

// Open打开指定的文件以进行读取。如果成功,返回的文件可以用于读取;关联的文件描述符的模式为O_RDONLY。
// 如果出现错误,错误类型将为*PathError。

这意味着它以只读模式打开文件。如果你检查newfile.WriteString()的错误,你会知道由于只读模式,没有写入任何内容。

英文:

The problem is in os.Open. If you check the documentation for this functions it says:

// Open opens the named file for reading. If successful, methods on
// the returned file can be used for reading; the associated file
// descriptor has mode O_RDONLY.
// If there is an error, it will be of type *PathError.

This means it opens file in read-only mode. If you would check the error of newfile.WriteString(). Then you would know, that nothing was written due to read-only mode.

huangapple
  • 本文由 发表于 2022年1月22日 16:17:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/70811111.html
匿名

发表评论

匿名网友

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

确定