无法在Go中读取utmpx文件。

huangapple go评论71阅读模式
英文:

Can not read utmpx file in go

问题

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} nil

> 0 nil

没有错误,也没有数据。

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

如何获取这个路径是另一个问题

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

**我的最终目标是将这个文件读入 go 结构体中。**这个文件包含了系统用户的信息。

**我能做到吗?**我会继续尝试...


<details>
<summary>英文:</summary>

    package main

    import (
     &quot;os&quot;
     &quot;fmt&quot;
    )

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

&gt; &amp;{0xc42000a240} nil

&gt; 0 nil

There is no error, also no data.

This path `/var/run/utmpx` is read from system header file. 

How to get this path is [another question][1]

system: macOS el capiton, go version go1.8 darwin/amd64

**My final goal is to read this file into go struct.**This file contains system users infomation.

**Can I do that ?** I will keep trying...

  [1]: https://stackoverflow.com/q/44036358/5819540

</details>


# 答案1
**得分**: 2

你可以使用`ioutil.ReadFile`函数来实现:

```go
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

英文:

You can use the ioutil.ReadFile function for this:

package main

import (
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
)

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

The problem in your original code is that you read into data that is 0 bytes long. Since the reader interface reads only reads up to len(data), it reads nothing. More on that: https://golang.org/pkg/io/#Reader

huangapple
  • 本文由 发表于 2017年7月25日 18:42:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/45300938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定