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.
- Using Create and WriteString Function
- 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:
OutputFile 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:
OutputFile created successfully!