To read and manipulate file attributes such as owner and group in Golang, you can use the os
package. The os
package provides several functions to retrieve file information and manipulate file properties. Here's an example:
import (
"fmt"
"os"
)
os.Stat
function. It returns a FileInfo
object that contains information about the file:fileInfo, err := os.Stat("/path/to/file")
if err != nil {
fmt.Println("Error:", err)
return
}
fileInfo.Sys().(*syscall.Stat_t).Uid
:ownerID := fileInfo.Sys().(*syscall.Stat_t).Uid
Note: This code requires importing the syscall
package.
fileInfo.Sys().(*syscall.Stat_t).Gid
:groupID := fileInfo.Sys().(*syscall.Stat_t).Gid
os.Chown
or os.Chgrp
functions:err = os.Chown("/path/to/file", newOwnerID, newGroupID)
if err != nil {
fmt.Println("Error:", err)
return
}
Note: Ensure you have appropriate permissions to change the owner or group of the file.
Remember to handle any potential errors when accessing the file attributes or performing file attribute manipulations.
This example demonstrates how to read and manipulate file attributes using the os
package in Golang.