go語言檔案基本操作

2021-10-03 06:43:49 字數 1187 閱讀 7820

const (

o_rdonly int = syscall.o_rdonly //唯讀模式開啟檔案

o_wronly int = syscall.o_wronly //只寫模式開啟檔案

o_rdwr int = syscall.o_rdwr //讀寫模式開啟檔案

o_create int = syscall.o_creat //如果不存在將建立乙個新檔案

o_excl int = syscall.o_excl //和o_create配合使用,檔案必須不存在

o_sync int = syscall.o_sync //開啟檔案用於同步i/o

o_trunc int = syscall.o_trunc //如果可能,開啟時清空檔案

)

func main() 

defer file.close() //關閉檔案

reader:=bufio.newreader(file) //帶緩衝區的讀寫

for ; ;

fmt.println("read string is %s: ",str)

}}

func main() 

defer file.close() //關閉檔案

buf,err:= ioutil.readall(file) //讀取整個檔案

if err!=nil

fmt.printf("%s\n",string(buf))

}

func main() 

defer file.close()

filestring:="張三李四"

file.seek(0,2) //最後增加

file.writestring(filestring)

}

func main() 

defer file.close()

filewrite:=bufio.newwriter(file)

filestring:="王麻子\n"

for i := 0; i<10; i++

filewrite.flush() //將緩衝中的資料寫入下層的io.writer介面(flush方法)

}

Go語言檔案操作

檔案的開啟和關閉 os.open 函式能夠開啟乙個檔案,返回乙個 file和乙個err。對得到的檔案例項呼叫close 方法能夠關閉檔案。為了防止檔案忘記關閉,我們通常使用defer註冊檔案關閉語句。讀取檔案 file.read read方法定義如下 func f file read b byte ...

go語言 檔案操作

os.open 函式能夠開啟乙個檔案,返回乙個 file和乙個err。對得到的檔案例項呼叫close 方法能夠關閉檔案。package main import fmt os func main 關閉檔案 file.close 為了防止檔案忘記關閉,我們通常使用defer註冊檔案關閉語句。read方法...

Go語言檔案操作

寫程式離不了檔案操作,這裡總結下 go語言檔案操作。一 建立與開啟 建立檔案函式 func create name string file file,err error func newfile fd int,name string file 具體見官網 開啟檔案函式 func open name ...