// flag.gopackagemainimport("flag""fmt")funcmain(){// 第一個參數 flag name, 第二個 default value, 第三個 flag descriptionfptr:=flag.String("fpath","test.txt","file path to read from")// 必須先執行,parse flagflag.Parse()fmt.Println("value of fpath is",*fptr)}
1
gorunflag.go-fpath=/path-of-file/test.txt
將之前的 test.txt 加上 flag 後
123456789101112131415161718
packagemainimport("flag""fmt""io/ioutil")funcmain(){fptr:=flag.String("fpath","test.txt","file path to read from")flag.Parse()data,err:=ioutil.ReadFile(*fptr)iferr!=nil{fmt.Println("File reading error",err)return}fmt.Println("Contents of file:",string(data))}
packagemainimport("fmt""github.com/gobuffalo/packr")funcmain(){box:=packr.NewBox("../filehandling")data,err:=box.FindString("test.txt")iferr!=nil{fmt.Println(err)}else{fmt.Println("Contents of file:",data)}}
packagemainimport("bufio""flag""fmt""log""os")funcmain(){// 先透過 flag 讀取參數fptr:=flag.String("fpath","test.txt","file path to read from")// 解析參數flag.Parse()// 打開檔案f,err:=os.Open(*fptr)iferr!=nil{log.Fatal(err)}// function 結束前關閉 filedeferfunc(){iferr=f.Close();err!=nil{log.Fatal(err)}}()// returns a new Reader whose buffer has the default size.r:=bufio.NewReader(f)// 建立 byte slice,容量 3,用來一次讀取 3 個b:=make([]byte,3)for{_,err:=r.Read(b)iferr!=nil{fmt.Println("Error reading file:",err)break}fmt.Println(string(b))}}