File Operations Guide
Core File Operations in Golang
Reading Files
Reading Entire File
func readEntireFile() {
content, err := os.ReadFile("/path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(content))
}
Reading Line by Line
func readLineByLine() {
file, err := os.Open("/path/to/file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
Writing Files
Writing Entire Content
func writeFile() {
data := []byte("Hello, LabEx!")
err := os.WriteFile("/path/to/output.txt", data, 0644)
if err != nil {
log.Fatal(err)
}
}
Appending to Files
func appendToFile() {
file, err := os.OpenFile("/path/to/file.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
if _, err := file.WriteString("New content\n"); err != nil {
log.Fatal(err)
}
}
File Operation Types
graph TD
A[File Operations] --> B[Read Operations]
A --> C[Write Operations]
A --> D[Management Operations]
B --> B1[ReadFile]
B --> B2[Read Line by Line]
C --> C1[WriteFile]
C --> C2[Append]
D --> D1[Create]
D --> D2[Delete]
D --> D3[Rename]
D --> D4[Check Existence]
File Permissions
Permission |
Numeric Value |
Meaning |
400 |
Read by owner |
|
600 |
Read/Write by owner |
|
644 |
Read by everyone, write by owner |
|
755 |
Read/Execute by everyone, full access by owner |
|
File Existence and Permissions
func checkFileStatus() {
// Check if file exists
_, err := os.Stat("/path/to/file.txt")
if os.IsNotExist(err) {
fmt.Println("File does not exist")
}
// Check permissions
fileInfo, _ := os.Stat("/path/to/file.txt")
fmt.Println("Permissions:", fileInfo.Mode())
}
Advanced File Handling
Temporary Files
func createTempFile() {
tempFile, err := os.CreateTemp("", "example*.txt")
if err != nil {
log.Fatal(err)
}
defer os.Remove(tempFile.Name())
defer tempFile.Close()
}
Error Handling Strategies
- Always check for errors
- Use
defer
for resource cleanup
- Handle specific error types
- Log or handle errors appropriately
LabEx Learning Tips
Practice these file operations on the LabEx platform to gain practical experience with real-world file management scenarios.