使用io/ioutil包讀取文件時報錯:open abc.txt: The system cannot find the file specified
原因是:ioutil.ReadFile()這個方法需要傳入決絕路徑的文件名
代碼:
const filename = "E:\\GoWorks\\Golang\\src\\if\\abc.txt"
//const filename = "abc.txt" //這樣寫會報錯
//contents, err := ioutil.ReadFile(filename) //讀取文件
//if err != nil {
// fmt.Println("err=",err)
//} else {
// fmt.Printf("%s\n", contents)
//}
//上面的寫法可以改為:
if contents, err := ioutil.ReadFile(filename); err != nil {
fmt.Println("err=", err)
} else {
fmt.Printf("%s\n", contents)
}
//注意:if的條件里可以賦值
//if的條件里賦值的變量作用域就在這個if語句里