无法在Go中读取utmpx文件。

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

Can not read utmpx file in go

问题

  1. package main
  2. import (
  3. "os"
  4. "fmt"
  5. )
  6. func main() {
  7. fd, err := os.Open("/var/run/utmpx")
  8. fmt.Println(fd, err)
  9. var data []byte
  10. len, err := fd.Read(data)
  11. fmt.Println(len, err)
  12. }

> &{0xc42000a240} nil

> 0 nil

没有错误,也没有数据。

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

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

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

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

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

  1. <details>
  2. <summary>英文:</summary>
  3. package main
  4. import (
  5. &quot;os&quot;
  6. &quot;fmt&quot;
  7. )
  8. func main() {
  9. fd, err := os.Open(&quot;/var/run/utmpx&quot;)
  10. fmt.Println(fd, err)
  11. var data []byte
  12. len, err := fd.Read(data)
  13. fmt.Println(len, err)
  14. }
  15. &gt; &amp;{0xc42000a240} nil
  16. &gt; 0 nil
  17. There is no error, also no data.
  18. This path `/var/run/utmpx` is read from system header file.
  19. How to get this path is [another question][1]
  20. system: macOS el capiton, go version go1.8 darwin/amd64
  21. **My final goal is to read this file into go struct.**This file contains system users infomation.
  22. **Can I do that ?** I will keep trying...
  23. [1]: https://stackoverflow.com/q/44036358/5819540
  24. </details>
  25. # 答案1
  26. **得分**: 2
  27. 你可以使用`ioutil.ReadFile`函数来实现:
  28. ```go
  29. package main
  30. import (
  31. "fmt"
  32. "io/ioutil"
  33. )
  34. func main() {
  35. fd, err := ioutil.ReadFile("/var/run/utmpx")
  36. fmt.Println(string(fd), err)
  37. }

你原始代码中的问题是你将数据读入了长度为0的data中。由于读取器接口只会读取len(data)长度的数据,所以它什么也没读取到。更多信息请参考:https://golang.org/pkg/io/#Reader

英文:

You can use the ioutil.ReadFile function for this:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;io/ioutil&quot;
  5. )
  6. func main() {
  7. fd, err := ioutil.ReadFile(&quot;/var/run/utmpx&quot;)
  8. fmt.Println(string(fd), err)
  9. }

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:

确定