open abc.txt: The system cannot find the file specified


使用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語句里


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM