English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Error

Golang Miscellaneous

Go File I/O(File operations)

In operation, the os.file object is used for file operations. The os.File object is also known as a file handle.

The open function in the os package is used to open files in Go.

io / The ReadFile() function in the ioutil package is used to read files, and this method returns an array of bytes[] of the read bytes. The file.WriteString method can be used to write to the file.

We immediately use defer file.close() after opening the file to ensure that the file is closed immediately after the function is completed. If the file does not exist or the program does not have sufficient permissions to open the file, then inputFile, inputError = os.Open("input.dat") will cause an error.

Go File I / OExample

package main
import (
   "os"
   "log"
   "io"/ioutil
   "fmt"
)
func main() {
   file, err := os.Create("file.txt")
   if err != nil {
      log.Fatal(err)
   
   file.WriteString("Hi... there")
   file.Close()
   stream, err := ioutil.ReadFile("file.txt")
   if err != nil {
      log.Fatal(err)
   
   readString := string(stream)
   fmt.Println(readString)

Output:

Hi... there