How to open and read the contents of a system file (e.g., /etc/passwd) using the os package in Golang?

To open and read the contents of a system file in Golang using the os package, you can follow these steps:

  1. Import the os package:
import "os"
  1. Use the Open() function from the os package to open the file. It returns a file descriptor and an error (if any).
file, err := os.Open("/etc/passwd") if err != nil { panic(err) } defer file.Close()
  1. Use the Read() function from the os package to read the contents of the file. It takes a byte slice as an argument and returns the number of bytes read and an error (if any).
buf := make([]byte, 1024) n, err := file.Read(buf) if err != nil { panic(err) }
  1. Use the string() function to convert the byte slice to a string and print the contents.
contents := string(buf[:n]) fmt.Println(contents)

Here's the complete example:

package main import ( "fmt" "os" ) func main() { file, err := os.Open("/etc/passwd") if err != nil { panic(err) } defer file.Close() buf := make([]byte, 1024) n, err := file.Read(buf) if err != nil { panic(err) } contents := string(buf[:n]) fmt.Println(contents) }

Make sure to handle any errors that can occur when opening or reading the file using appropriate error handling techniques.