打开和写入文件时出现错误。

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

Error in opening and writing to a file

问题

我想打开一个文件并向其中写入一些文本,但是我遇到了以下错误:

.\hello.go:13: cannot use msg (type string) as type []byte in argument to f.Write

以下是我目前的代码:

package main

import (
	"os"
)

func printer(msg string) (err error) {
	f, err := os.Create("helloworld.txt")
	if err != nil {
		return err
	}
	defer f.Close()
	f.Write(msg)
	return err
}

func main() {
	printer("Hello World")
}
英文:

I want to open a file and write some text to it, however I get the following error:

.\hello.go:13: cannot use msg (type string) as type []byte in argument to f.Write

Here's my code so far:

package main

import (
	"os"
)

func printer(msg string) (err error) {
	f, err := os.Create("helloworld.txt")
	if err != nil {
		return err
	}
	defer f.Close()
	f.Write(msg)
	return err
}

func main() {
	printer("Hello World")
}

答案1

得分: 5

使用io.WriteString(f, msg)f.Write([]byte(msg))io.Copy(f, strings.NewReader(msg))

英文:

Use io.WriteString(f, msg), f.Write([]byte(msg)) or io.Copy(f, strings.NewReader(msg)).

huangapple
  • 本文由 发表于 2015年4月18日 19:45:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/29716874.html
匿名

发表评论

匿名网友

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

确定