Open In App

Go Language Program to write data in a text file

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to see how we can write any text file in the Go language. Go language provides many standard libraries, and we are using the 'os' package, which is used to perform all read/write operations. There are many ways to create a file in the Go language, which can be achieved as follows.

  1. Using Create and WriteString Function
  2. Using WriteFile Function

Method 1: Using Create and WriteString Function

  • os.Create() creates or truncates the named file, this simply means if file exists then it will open it and remove all the contents from(make it empty) or create a new named file. It returns file and error if any.
  • os.WriteString is use to write the content inside the file. It return the total number of bytes of the content of type int and error if any.

Syntax:

func Create(fileName string) (*File, error)
func (f *File) WriteString(data string) (n int, err error)

Parameters:

  • fileName: It takes the name of the file along with path. (Provide only name if you want to create in same directory)
  • data: It takes data which we have to write in file.

Code Example:

Go
package main

import (
	"fmt"
	"os"
)

func main() {
	// Define the string to be written to the file
	var myString = "Welcome to GeeksforGeeks"

	// Create a new file named "myfile.txt" in the same directory
	file, err := os.Create("myfile.txt")
	if err != nil { // Check for an error during file creation
		panic(err)
	}
	defer file.Close() // Ensure the file is closed when the function exits

	// Write the string data to the file
	_, err = file.WriteString(myString)
	if err != nil { // Check for an error during file write
		panic(err)
	}

	fmt.Println("File written successfully.")
}

Output
File written successfully.

Method 2: Using Create and WriteString Function

  • os.WriteFile creates or truncates the named file, this simply means if file exists then it will open it and remove all the contents from(make it empty) or create a new named file. It returns error if any.

Syntax:

func WriteFile(name string, data []byte, perm FileMode) error

Parameters:

  • name: It take the name of the file along with the file path.
  • data: It take Slice of the data bytes which we have to write in file.
  • prem: It take value for the permission for the file.(We will use read and write permisssion)

Code Example:

Go
package main

import (
	"fmt"
	"os"
)

func main() {
	myString := "Welcome to GeeksforGeeks"

	// Convert the string to a byte slice
	bytes := []byte(myString)

	// Write the byte slice to a file with read and write permissions for everyone
	err := os.WriteFile("myfile.txt", bytes, 0666)
	if err != nil {
		panic("Failed to write file")
	}

	// Print a success message
	fmt.Println("File created successfully!")
}

Output
File created successfully!

Next Article

Similar Reads