Easiest way to append to a file

1,244 views
Skip to first unread message

Frank Blechschmidt

unread,
Oct 1, 2012, 10:57:20 AM10/1/12
to golan...@googlegroups.com
Hey,

I try to write a little logging package for my program.
It should create a file if it doesn't exist and append a given input (string) into this file.
Most functions I tried so far overwrite the textfile :(

func WriteEntry (logfiletype, entry string){
datestamp := time.Now()
datestampstring := datestamp.String()
datestampstring = datestampstring[0:10]
datestampstring = logfiletype + "-" + datestampstring
os.Chdir("../logs")
logfile,_ := os.Create(datestampstring)
logfile.WriteString(entry)
logfile.Close()
}

Thanks
Frank

Jan Mercl

unread,
Oct 1, 2012, 11:04:38 AM10/1/12
to Frank Blechschmidt, golan...@googlegroups.com
Instead of os.Create better is probably os.OpenFile(name,
os.O_WRONLY|os.O_APPEND|os.O_CREATE, perm) in this case.

cf: http://golang.org/pkg/os/#OpenFile

-j

Frank Blechschmidt

unread,
Oct 1, 2012, 11:08:23 AM10/1/12
to golan...@googlegroups.com, Frank Blechschmidt
Works fine! Many thanks :D
Reply all
Reply to author
Forward
0 new messages