Home  >  Article  >  Backend Development  >  How to write Golang file reading and writing functions?

How to write Golang file reading and writing functions?

王林
王林Original
2024-06-06 11:07:57828browse

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.

如何编写 Golang 文件读写函数?

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.

Read file

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))

Write file

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)
}

Other I/ O operations

In addition to read and write operations, Go also provides other I/O operations, such as:

  • Open file:f, err := os.Open("filename.txt")
  • Close the file: f.Close()
  • Read the file information: fi , err := os.Stat("filename.txt")
  • Create directory: err := os.Mkdir("my_directory", 0755)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn