{"id":1181,"date":"2020-01-17T16:41:27","date_gmt":"2020-01-17T16:41:27","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=1181"},"modified":"2020-01-17T16:41:31","modified_gmt":"2020-01-17T16:41:31","slug":"append-file-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/append-file-golang\/","title":{"rendered":"Append to an existing file in Go (Golang)"},"content":{"rendered":"\n
os.OpenFile()<\/strong> function of the os package can be used to open to a file in an append mode and then write to it<\/p>\n\n\n\n Let’s see an example. In the below program:<\/p>\n\n\n\n Output:<\/strong><\/p>\n\n\n\n os.OpenFile() function of the os package can be used to open to a file in an append mode and then write to it Let’s see an example. In the below program: First,…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[38,3],"class_list":["post-1181","post","type-post","status-publish","format-standard","hentry","category-tech","tag-file","tag-go"],"yoast_head":"\npackage main\n\nimport (\n \"fmt\"\n \"io\/ioutil\"\n \"log\"\n \"os\"\n)\n\nfunc main() {\n \/\/Write first line\n err := ioutil.WriteFile(\"temp.txt\", []byte(\"first line\\n\"), 0644)\n if err != nil {\n log.Fatal(err)\n }\n \n \/\/Append second line\n file, err := os.OpenFile(\"temp.txt\", os.O_APPEND|os.O_WRONLY, 0644)\n if err != nil {\n log.Println(err)\n }\n defer file.Close()\n if _, err := file.WriteString(\"second line\"); err != nil {\n log.Fatal(err)\n }\n \n \/\/Print the contents of the file\n data, err := ioutil.ReadFile(\"temp.txt\")\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(string(data))\n}<\/code><\/pre>\n\n\n\n
first line\nsecond line<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"