In Golang, handling file operations primarily involves packages such as os and io/ioutil. Below are common file operation steps and code examples:
1. Opening and Reading Files
To open and read file content, use the os.Open function to open the file, followed by ioutil.ReadAll or bufio.Scanner for reading.
gopackage main import ( "bufio" "fmt" "os" ) func main() { file, err := os.Open("example.txt") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Println("Error reading file:", err) } }
2. Creating and Writing Files
To create and write to a file, use os.Create to create the file, then employ fmt.Fprintln or bufio.Writer for writing.
gopackage main import ( "bufio" "fmt" "os" ) func main() { file, err := os.Create("example.txt") if err != nil { fmt.Println("Error creating file:", err) return } defer file.Close() writer := bufio.NewWriter(file) _, err = writer.WriteString("Hello, Golang!\n") if err != nil { fmt.Println("Error writing to file:", err) } writer.Flush() }
3. File Information and Permissions
Using os.Stat retrieves file information such as size and permissions.
gopackage main import ( "fmt" "os" ) func main() { fileInfo, err := os.Stat("example.txt") if err != nil { fmt.Println("Error getting file info:", err) return } fmt.Println("File name:", fileInfo.Name()) fmt.Println("Size in bytes:", fileInfo.Size()) fmt.Println("Permissions:", fileInfo.Mode()) }
4. Copying Files
Utilize the io.Copy function to copy file content.
gopackage main import ( "io" "os" ) func main() { sourceFile, err := os.Open("source.txt") if err != nil { fmt.Println("Error opening source file:", err) return } defer sourceFile.Close() destFile, err := os.Create("dest.txt") if err != nil { fmt.Println("Error creating destination file:", err) return } defer destFile.Close() _, err = io.Copy(destFile, sourceFile) if err != nil { fmt.Println("Error copying file:", err) } }
These operations cover common file handling requirements in daily development. The implementation of each feature can be adjusted or optimized based on specific needs.
2024年10月26日 16:54 回复