Home >Backend Development >Golang >How to operate files in golang
In the Go language, reading and modifying files is a very common requirement. In this article, we will introduce how to operate files, including opening files, deleting file contents, obtaining file information, and restoring files to their original state.
1. Open the file
Use the os.OpenFile() function to open the file. This function can accept many parameters. In this case, we just pass in the filename and flag.
File flags are changed as needed. For example, if you want to append content to the end of the file, you need to set the flag to os.O_APPEND | os.O_WRONLY.
Sample code:
f, err := os.OpenFile("example.txt", os.O_RDWR, 0644) if err != nil { log.Fatal(err) } defer f.Close()
2. Delete the file content
Use the os.Truncate() function to delete the file content. This function accepts an offset parameter and a length parameter. The offset represents the starting position of the file to be truncated, and the length represents the number of bytes to be truncated.
Sample code:
err := os.Truncate("example.txt", 0) if err != nil { log.Fatal(err) }
3. Obtain file information
Use the os.Stat() function to obtain the metadata of the file. The metadata obtained includes file size, modification time, file mode, etc.
Sample code:
fi, err := os.Stat("example.txt") if err != nil { log.Fatal(err) } fmt.Println(fi.Size()) fmt.Println(fi.Mode()) fmt.Println(fi.ModTime())
4. Restore the file to its original state
If you want to restore the file to its original state, you need to write Load the old content before adding the new content, and then write the old content back to the file.
Sample code:
// 读取原始内容 b, err := ioutil.ReadFile("example.txt") if err != nil { log.Fatal(err) } // 写入新内容 _, err = fmt.Fprint(f, "new content") if err != nil { log.Fatal(err) } // 将原始内容写回去 _, err = f.Seek(0, 0) if err != nil { log.Fatal(err) } _, err = f.Write(b) if err != nil { log.Fatal(err) }
The above is a simple file modification operation. I hope this article can help!
The above is the detailed content of How to operate files in golang. For more information, please follow other related articles on the PHP Chinese website!