【问题标题】:Can not read utmpx file in go无法在 go 中读取 utmpx 文件
【发布时间】:2017-07-25 10:42:07
【问题描述】:
package main

import (
 "os"
 "fmt"
)

func main() {
  fd, err := os.Open("/var/run/utmpx")
  fmt.Println(fd, err)
  var data []byte
  len, err := fd.Read(data)
  fmt.Println(len, err)
}

&{0xc42000a240} 无

0 无

没有错误,也没有数据。

此路径/var/run/utmpx 是从系统头文件中读取的。

如何得到这个路径是another question

系统:macOS el capiton,go 版本 go1.8 darwin/amd64

**我的最终目标是将此文件读入 go struct。**此文件包含系统用户信息。

我可以这样做吗?我会继续努力...

【问题讨论】:

  • 您是否以管理员权限运行脚本?
  • @mic4ael 嗨,我使用的是 macOS,我使用 go run main.go 运行它,如何使用 root 运行它?
  • sudo go run main.go
  • data 的长度为 0(它为 nil),因此您正在尝试读取 0 个字节。
  • @mic4ael go: cannot find GOROOT directory: /usr/local/go got this error

标签: c macos unix go


【解决方案1】:

您可以为此使用ioutil.ReadFile 函数:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    fd, err := ioutil.ReadFile("/var/run/utmpx")
    fmt.Println(string(fd), err)
}

原始代码中的问题是您读入了 0 字节长的 data。由于阅读器界面只读取到len(data),它什么也不读。更多信息:https://golang.org/pkg/io/#Reader

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-04
    • 2016-08-11
    • 2014-02-17
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多