Go Program to Write a File

Go Program to Write a File

In Go programming, io package is used to work with file operations.

WriteFile function in io package is used to write message into a file.

Sample Go program explains how to write string data into a file.

package main                                                               	 
                                                                           	 
import (                                                                   	 
	"fmt"                                                                  	 
	"io/ioutil"                                                            	 
)                                                                          	 
                                                                           
// writes message into a file	 
func writeFile(msg string) {                                               	 
	bytes := []byte(msg)                                                   	 
	ioutil.WriteFile("test.txt", bytes, 0644)                              	 
}                                                                          	 
                                                                           	 
func main() {                                                              	 
	var msg string                                                         	 
                                                                           	 
	fmt.Print("Enter message to write in file:")                           	 
	fmt.Scanf("%s", &msg)                                                  	 
                                                                           	 
	writeFile(msg)                                                         	 
                                                                           	 
	fmt.Println("\nFile is created: test.txt")                             	 
                                                                           	 
} 
Output:
$ go build write-file.go
$ ./write-file
Enter message to write in file:codingpointer.com!

File is created: test.txt
$ cat test.txt
codingpointer.com!