Home > Article > Backend Development > How to write Golang file reading and writing functions?
The Go language uses the I/O library to efficiently read and write files. To read a file, use ReadFile to return a byte array; to write a file, use WriteFile to write a byte array. In addition, Go supports other I/O operations such as opening files, closing files, reading file information, and creating directories.
How to write Go file reading and writing functions
The Go language provides a wide range of I/O libraries for efficiently interacting with File read and write operations. This article will introduce how to write Go functions for file reading and writing, including practical cases.
The following function reads the content from the given file and returns a byte array:
func readFile(filename string) ([]byte, error) { data, err := ioutil.ReadFile(filename) if err != nil { return nil, err } return data, nil }
Practical case:
data, err := readFile("data.txt") if err != nil { log.Fatalf("Failed to read file: %v", err) } fmt.Println(string(data))
The following function writes the byte array to the given file:
func writeFile(filename string, data []byte) error { err := ioutil.WriteFile(filename, data, 0644) if err != nil { return err } return nil }
Practical case:
data := []byte("Hello, world!") err := writeFile("hello.txt", data) if err != nil { log.Fatalf("Failed to write file: %v", err) }
In addition to read and write operations, Go also provides other I/O operations, such as:
The above is the detailed content of How to write Golang file reading and writing functions?. For more information, please follow other related articles on the PHP Chinese website!