Handle Files
Create a File
To create a file, you can use the os.Create
function along with the defer statement to close the file after writing to it.
Example
Write into a File
Open the file in append mode
and write to it using the os.OpenFile
function.
Example
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.OpenFile("src/handle_files/example.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
size, err := file.WriteString("\nWriting a string into the file\n")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Size written into file: ", size)
_, err = file.Write([]byte("Using bytes to write"))
}
File Permission Number
In the os.OpenFile
function, the perm argument is used to specify the file permission when creating or opening a file
. It is an integer value that represents the file mode and permission bits. The typical file permission values used in Unix-like systems are represented in octal notation. The permission mode is composed of three digits, each of which represents the permissions for different user groups
.
Owner Permissions
: The first digit represents the permissions for the file owne.Group Permissions
: The second digit represents the permissions for the group that the file belongs to.Other Permissions
: The third digit represents the permissions for everyone else (other users).
The digits in the mode are a sum of permission bits:
4: Read (r)
2: Write (w)
1: Execute (x)
And calculate the permissions numbers:
6 (4 + 2) means read and write permissions (rw)
.4 (only 4) means read-only (r).
.7 (4 + 2 + 1) means read, write, and execute permissions (rwx).
.
Example
0644
: Owner has read and write (6), group and others have read-only (4).0755
: Owner has read, write, and execute (7), group and others have read and execute (5).0600
: Owner has read and write (6), no permissions for group and others.
Reading a File
To read from a file, you can use the os.Open
function along with a Scanner from the bufio package
.
Example
Delete a File
To delete a file, you can use the os.Remove
function.