英文:
Go: Write carriage return with IO
问题
我正在尝试使用IO.WriteString在Go语言中写入文件,但即使写入"\n"字符,它也不会打印换行符。我认为可能不是换行符本身需要写入,在Windows中,如果我用Wordpad打开txt文件,换行符会显示出来,但在记事本中不会显示。
对于这种行为有什么想法吗?以下是代码:
//写入
t := time.Now().Local()
src, err := os.Stat("/dir")
if err != nil {
log.Println(err, log.Llongfile)
}
if !src.IsDir() {
err = errors.New("文件夹不存在")
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")
使用这段代码,在Windows记事本中打开txt文件的结果是"Hello WorldGoodbye"。
谢谢。
英文:
I'm trying to write on a file in Go with IO.WriteString, but even writing "\n" character it does not print the carriage return. I think maybe is not the carriage return itself what i need to write, in Windows, if i open the txt file with Wordpad, the carriage return is shown, but not in the notepad.
Any ideas about this behaviour?, here is the code:
//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")
With this code, the result in the txt file is "Hello WorldGoodbye" if i open it in Windows notepad.
Thanks.
答案1
得分: 8
问题出在Windows对回车符的期望方式上,"\n"是Unix的方式,"\r\n"是Windows的方式。
所以,只需要替换一下就可以解决问题。
n, err := io.WriteString(f, "Hello World\r\n")
英文:
The problem was the way Windows expects carriage return, "\n" is Unix way, and "\r\n" is Windows way.
So, just replacing it does the trick.
n, err := io.WriteString(f, "Hello World\r\n")
答案2
得分: 4
回车符是 \r
而不是 \n
。
英文:
Carriage return is \r
not \n
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论