实验环境:
IOS 系统下安装的 go 开发环境。使用 VScode 编译。
实验步骤:
建立一个结构体:存储命令的参数
type selpgArgs struct {
startPage int
endPage int
inFilename string
pageLen int
pageType bool
printDest string
}
之后通过使用 flag 库解析参数,把输入的命令行参数绑定到结构体的每一个变量
func get(pageArg *selpgArgs) {
flag.IntVar(&pageArg.startPage, "s", -1, "Start page.")
flag.IntVar(&pageArg.endPage, "e", -1, "End page.")
flag.IntVar(&pageArg.pageLen, "l", 72, "Line number per page.")
flag.BoolVar(&pageArg.pageType, "f", false, "Determine form-feed-delimited")
flag.StringVar(&pageArg.printDest, "d", "", "specify the pager")
flag.Parse()
argsleft := flag.Args()
if len(argsleft) > 0 {
pageArg.inFilename = string(argsleft[0])
} else {
pageArg.inFilename = ""
}
}
之后根据参数来执行命令,代码如下:
func processInput(pageArg *selpgArgs) {
var inFile *os.File
var outFile *os.File
var outFileDestion io.WriteCloser
if pageArg == nil {
fmt.Fprintf(os.Stderr, "\n[Error]The args is nil!\n")
os.Exit(1)
} else if pageArg.startPage == -1 || pageArg.endPage == -1 {
fmt.Fprintf(os.Stderr, "\n[Error]The startpage or endpage is nil!\n")
os.Exit(2)
} else if pageArg.startPage < 0 || pageArg.endPage < 0 {
fmt.Fprintf(os.Stderr, "\n[Error]The startpage or endpage is illegal!\n")
os.Exit(3)
} else if pageArg.startPage > pageArg.endPage {
fmt.Fprintf(os.Stderr, "\n[Error]The startpage can not bigger than endpage !\n")
os.Exit(4)
}
if pageArg.inFilename == "" {
inFile = os.Stdin
} else {
var errorInFile error
inFile, errorInFile = os.Open(pageArg.inFilename)
if errorInFile != nil {
fmt.Fprintf(os.Stderr, "\n[Error]I]input File :")
panic(errorInFile)
}
}
if len(pageArg.printDest) == 0 {
outFile = os.Stdout
outFileDestion = nil
} else {
outFile = nil
var errorDest error
cmd := exec.Command("./" + pageArg.printDest)
outFileDestion, errorDest = cmd.StdinPipe()
if errorDest != nil {
fmt.Fprintf(os.Stderr, "\n[Error]outFileDestion:")
panic(errorDest)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
errorStart := cmd.Start()
if errorStart != nil {
fmt.Fprintf(os.Stderr, "\n[Error]command-start:")
panic(errorStart)
}
}
if outFile != nil {
lineCount := 0
pageCount := 1
buf := bufio.NewReader(inFile)
for {
line, err := buf.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
fmt.Fprintf(os.Stderr, "\n[Error]readfile")
}
lineCount++
if lineCount > pageArg.pageLen {
pageCount++
lineCount = 1
}
if (pageCount >= pageArg.startPage) && (pageCount <= pageArg.endPage) {
fmt.Fprintf(outFile, "%s", line)
}
}
} else {
lineCount := 0
pageCount := 1
buf := bufio.NewReader(inFile)
for {
bytes, err := buf.ReadByte()
if err == io.EOF {
break
}
if lineCount > pageArg.pageLen {
pageCount++
lineCount = 1
}
if (pageCount >= pageArg.startPage) && (pageCount <= pageArg.endPage) {
outFileDestion.Write([]byte{bytes})
}
}
}
}
这样就完成了。
实验结果:
因为文件名为 main,所以命令的名字也是 main
分享链接: http://139.9.57.167:20080/share/bmda99e76kvrcg19tf20?secret=false