Go:用IO写回车

afb*_*ros 2 go

我正在尝试使用 IO.WriteString 在 Go 中写入文件,但即使写入 "\n" 字符,它也不会打印回车符。我想可能不是我需要写的回车本身,在Windows中,如果我用写字板打开txt文件,会显示回车,但不在记事本中。

关于这种行为的任何想法?,这里是代码:

//Write
t := time.Now().Local()
src, err := os.Stat("/dir")
if err != nil {
    log.Println(err, log.Llongfile)
}
if !src.IsDir() {
    err = errors.New("Folder does not exists")
    log.Println(err, log.Llongfile)
    err = os.MkdirAll("/dir", 665)
    log.Println(err, log.Llongfile)
}
f, err := os.Create("/dir" + "/File_" + t.Format("20060102") + ".txt")
n, err := io.WriteString(f, "Hello World\n")
n, err = io.WriteString(f, "Goodbye\n")
Run Code Online (Sandbox Code Playgroud)

使用此代码,如果我在 Windows 记事本中打开它,txt 文件中的结果是“Hello WorldGoodbye”。

谢谢。

afb*_*ros 5

问题是 Windows 期望回车的方式,“\n”是 Unix 方式,而“\r\n”是 Windows 方式。

所以,只需更换它就可以了。

n, err := io.WriteString(f, "Hello World\r\n")
Run Code Online (Sandbox Code Playgroud)