Open In App

How to Read and Write the Files in Golang?

Golang offers a vast inbuilt library that can be used to perform read and write operations on files. In order to read from files on the local system, the io/ioutil module is put to use. The io/ioutil module is also used to write content to the file. 
The fmt module implements formatted I/O with functions to read input from the stdin and print output to the stdout. The log module implements simple logging package. It defines a type, Logger, with methods for formatting the output. The os module provides the ability to access native operating-system features. The bufio module implements buffered I/O which helps to improve the CPU performance.
 

Example 1: Use the offline compiler for better results. Save the file with .go extension. Use the command below command to execute the program.
 



go run filename.go

 




// Golang program to read and write the files
package main
 
// importing the packages
import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
)
 
func CreateFile() {
 
    // fmt package implements formatted
    // I/O and has functions like Printf
    // and Scanf
    fmt.Printf("Writing to a file in Go lang\n")
     
    // in case an error is thrown it is received
    // by the err variable and Fatalf method of
    // log prints the error message and stops
    // program execution
    file, err := os.Create("test.txt")
     
    if err != nil {
        log.Fatalf("failed creating file: %s", err)
    }
     
    // Defer is used for purposes of cleanup like
    // closing a running file after the file has
    // been written and main //function has
    // completed execution
    defer file.Close()
     
    // len variable captures the length
    // of the string written to the file.
    len, err := file.WriteString("Welcome to GeeksforGeeks."+
            " This program demonstrates reading and writing"+
                         " operations to a file in Go lang.")
 
    if err != nil {
        log.Fatalf("failed writing to file: %s", err)
    }
 
    // Name() method returns the name of the
    // file as presented to Create() method.
    fmt.Printf("\nFile Name: %s", file.Name())
    fmt.Printf("\nLength: %d bytes", len)
}
 
func ReadFile() {
 
    fmt.Printf("\n\nReading a file in Go lang\n")
    fileName := "test.txt"
     
    // The ioutil package contains inbuilt
    // methods like ReadFile that reads the
    // filename and returns the contents.
    data, err := ioutil.ReadFile("test.txt")
    if err != nil {
        log.Panicf("failed reading data from file: %s", err)
    }
    fmt.Printf("\nFile Name: %s", fileName)
    fmt.Printf("\nSize: %d bytes", len(data))
    fmt.Printf("\nData: %s", data)
 
}
 
// main function
func main() {
 
    CreateFile()
    ReadFile()
}

Output:
 



Example 2: Golang Program code that accepts user input to read and write the files.
 




// Golang program to read and write the files
package main
 
// importing the requires packages
import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
)
 
func CreateFile(filename, text string) {
 
    // fmt package implements formatted I/O and
    // contains inbuilt methods like Printf
    // and Scanf
    fmt.Printf("Writing to a file in Go lang\n")
     
    // Creating the file using Create() method
    // with user inputted filename and err
    // variable catches any error thrown
    file, err := os.Create(filename)
     
    if err != nil {
        log.Fatalf("failed creating file: %s", err)
    }
     
    // closing the running file after the main
    // method has completed execution and
    // the writing to the file is complete
    defer file.Close()
     
    // writing data to the file using
    // WriteString() method and the
    // length of the string is stored
    // in len variable
    len, err := file.WriteString(text)
    if err != nil {
        log.Fatalf("failed writing to file: %s", err)
    }
 
    fmt.Printf("\nFile Name: %s", file.Name())
    fmt.Printf("\nLength: %d bytes", len)
}
 
func ReadFile(filename string) {
 
    fmt.Printf("\n\nReading a file in Go lang\n")
     
    // file is read using ReadFile()
    // method of ioutil package
    data, err := ioutil.ReadFile(filename)
     
    // in case of an error the error
    // statement is printed and
    // program is stopped
    if err != nil {
        log.Panicf("failed reading data from file: %s", err)
    }
    fmt.Printf("\nFile Name: %s", filename)
    fmt.Printf("\nSize: %d bytes", len(data))
    fmt.Printf("\nData: %s", data)
 
}
 
// main function
func main() {
 
    // user input for filename
    fmt.Println("Enter filename: ")
    var filename string
    fmt.Scanln(&filename)
 
    // user input for file content
    fmt.Println("Enter text: ")
    inputReader := bufio.NewReader(os.Stdin)
    input, _ := inputReader.ReadString('\n')
     
    // file is created and read
    CreateFile(filename, input)
    ReadFile(filename)
}

Output:
 

 


Article Tags :