Golang 檔案讀寫操作

2021-09-12 18:57:07 字數 797 閱讀 8286

package main

import (

"fmt"

"io"

"log"

"os"

"path/filepath"

"strconv"

)func main()

strfile := strdir + "\\testfile.txt"

fmt.println("file to open is ", strfile)

// 開啟檔案,如果沒有,那麼建立,設定為讀寫操作,檔案許可權為755

file, erropenfile := os.openfile(strfile, os.o_rdwr|os.o_create, 755)

if erropenfile != nil

// 保證檔案能夠被關閉

defer file.close()

// 寫檔案

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

szbuf := make(byte, 1024)

// 讀檔案

// 由於對file進行的寫操作已經將檔案指標偏移到檔案末尾

// 如果此處用read,會導致失敗,因此使用readat,且從檔案開頭讀取

nread, errread := file.readat(szbuf, 0)

if errread != nil && errread != io.eof

fmt.printf("read size:%d, content:%s", nread, szbuf)

}

go lang 讀寫檔案操作

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

golang 檔案讀寫操作

實現php file get contents,file put contents 函式 package php import errors os strings sync var mu sync.mutex unsupportprotocols 暫時不支援的協議型別 var unsupportpr...

Golang對檔案讀寫操作

package main import bufio fmt io os 寫func writefile path string 使用完畢,需要關閉檔案 defer f.close var buf string for i 0 i 5 i fmt.println n n 讀檔案內容方法 func re...