code.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type file struct {
  10. name string
  11. size int
  12. }
  13. type dir struct {
  14. name string
  15. parent *dir
  16. dirs []dir
  17. files []file
  18. }
  19. func cd(line string, current *dir, dirsRead map[string]*dir, root *dir) *dir {
  20. var name string
  21. n, err := fmt.Sscanf(line, "$ cd %s", &name)
  22. if n != 1 || err != nil {
  23. log.Fatal("Can't parse cd:", err)
  24. }
  25. if name == "/" {
  26. current = root
  27. } else if name == ".." {
  28. current = current.parent
  29. } else {
  30. parent := current
  31. current, _ = dirsRead[name]
  32. if current == nil {
  33. newDir := dir{name: name, parent: parent}
  34. parent.dirs = append(parent.dirs, newDir)
  35. current = &newDir
  36. fmt.Println(name, current, newDir)
  37. dirsRead[name] = current
  38. }
  39. }
  40. return current
  41. }
  42. func readInput(file *os.File) dir {
  43. scanner := bufio.NewScanner(file)
  44. root := dir{name: "/"}
  45. dirsRead := make(map[string]*dir)
  46. var current *dir
  47. for scanner.Scan() {
  48. line := scanner.Text()
  49. if line == "" {
  50. continue
  51. }
  52. if strings.HasPrefix(line, "$ cd") {
  53. current = cd(line, current, dirsRead, &root)
  54. fmt.Println(line, current)
  55. }
  56. }
  57. return root
  58. }
  59. func main() {
  60. if len(os.Args) < 2 {
  61. log.Fatal("You need to specify a file!")
  62. }
  63. filePath := os.Args[1]
  64. file, err := os.Open(filePath)
  65. if err != nil {
  66. log.Fatalf("Failed to open %s!\n", filePath)
  67. }
  68. root := readInput(file)
  69. fmt.Println(root)
  70. }