Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Write carriage return with IO [duplicate]

Tags:

go

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.

like image 709
afboteros Avatar asked Sep 03 '25 15:09

afboteros


1 Answers

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")
like image 182
afboteros Avatar answered Sep 05 '25 04:09

afboteros