Steps to create and manage files in Go language: Use the os.Create function to create files. Open the file using the os.Open function. Use the File object's WriteString method to write to the file. Use the io.ReadAll function to read files. Use the os.Remove function to delete files.
How to use Go language to create and manage files
Create files
Use os.Create
Function creates a new file:
package main import ( "fmt" "os" ) func main() { f, err := os.Create("test.txt") if err != nil { fmt.Println(err) return } fmt.Println("File created successfully") defer f.Close() }
Open a file
Open an existing file using the os.Open
function :
func main() { f, err := os.Open("test.txt") if err != nil { fmt.Println(err) return } fmt.Println("File opened successfully") defer f.Close() }
Write a file
Use the WriteString
method of the File object to write a file:
func main() { f, err := os.OpenFile("test.txt", os.O_WRONLY, 0644) if err != nil { fmt.Println(err) return } _, err = f.WriteString("Hello, world!") if err != nil { fmt.Println(err) return } fmt.Println("File written successfully") defer f.Close() }
Read a file
Use io.ReadAll
function to read files:
func main() { f, err := os.Open("test.txt") if err != nil { fmt.Println(err) return } data, err := io.ReadAll(f) if err != nil { fmt.Println(err) return } fmt.Println("File read successfully:", string(data)) defer f.Close() }
Delete files
Use os.Remove
Function to delete files:
func main() { err := os.Remove("test.txt") if err != nil { fmt.Println(err) return } fmt.Println("File deleted successfully") }
The above is the detailed content of How to create and manage files using Golang?. For more information, please follow other related articles on the PHP Chinese website!