2020年6月19日金曜日

開発環境

Go Systems Programming: Master Linux and Unix system level programming with Go (Mihalis Tsoukalos(著)、Packt Publishing)のChapter 5(Files and Directories)、Exercises 5.の解答を求めてみる。

コード

package main

import (
 "flag"
 "fmt"
 "os"
 "path/filepath"
)

func main() {
 minusR := flag.Bool("R", false, "Recursively list subdirectories encountered.")
 flag.Parse()
 files := flag.Args()
 if len(files) == 0 {
  files = []string{"."}
 }
 walkFun := func(path string, info os.FileInfo, err error) error {
  fileInfo, err := os.Stat(path)
  if err != nil {
   fmt.Fprintln(os.Stderr, err)
   return err
  }
  pathBase := filepath.Base(path)
  if fileInfo.IsDir() {
   fmt.Printf("%v:\n", pathBase)
   pattern := filepath.Join(path, "*")
   names, err := filepath.Glob(pattern)
   if err != nil {
    fmt.Fprintln(os.Stderr, err)
    return err
   }
   for _, name := range names {
    name := filepath.Base(name)
    fmt.Printf("%v\t", name)
   }
   fmt.Println()
  }
  return nil
 }
 for _, file := range files {
  fileInfo, err := os.Stat(file)
  if err != nil {
   fmt.Fprintln(os.Stderr, err)
   continue
  }
  if fileInfo.IsDir() {
   if *minusR {
    err := filepath.Walk(file, walkFun)
    if err != nil {
     fmt.Fprintln(os.Stderr, err)
    }
   } else {
    fmt.Printf("%v:\n", filepath.Base(file))
    pattern := filepath.Join(file, "*")
    names, err := filepath.Glob(pattern)
    if err != nil {
     fmt.Fprintln(os.Stderr, err)
     continue
    }
    for _, name := range names {
     name := filepath.Base(name)
     fmt.Printf("%v\t", name)
    }
    fmt.Println()
   }
  } else {
   file = filepath.Base(file)
   fmt.Printf("%v\t", file)
  }
 }
 fmt.Println()
}

入出力結果(Zsh、PowerShell、Terminal)

% go build
% ./ls 
.:
ls ls.go 

% ./ls ls
ls 
% ./ls ls ls.go
ls ls.go 
% ./ls -R ls ls.go
ls ls.go 
% ./ls ../ls 
ls:
ls ls.go 

% ./ls ../ls ../which ../rm
ls:
ls ls.go 
which:
which which.go 
rm:
rm rm.go 

% ./ls -R ../ls ../which ../rm
ls:
ls ls.go 
which:
which which.go 
rm:
rm rm.go 

% ./ls ..                     
..:
ls output.txt rm which 

% ./ls -R ..
..:
ls output.txt rm which 
ls:
ls ls.go 
rm:
rm rm.go 
which:
which which.go 

% 

0 コメント:

コメントを投稿