golang 檔案讀寫操作

2021-10-09 08:20:41 字數 1563 閱讀 6584

實現php file_get_contents,file_put_contents 函式

package php

import (

"errors"

"os"

"strings"

"sync"

)var mu sync.mutex

//unsupportprotocols 暫時不支援的協議型別

var unsupportprotocols = string

//supportprotocols 支援的協議型別

var supportprotocols = "file://"

//file_default 檔案預設的寫入方式

const file_default = os.o_trunc

//file_create 寫入檔案不存在時自動建立

const file_create = os.o_create

//file_apend 追加方式寫入檔案

//filegetcontents php file_get_contents 實現

func filegetcontents(path string) (string, error)

} if strings.index(path, supportprotocols) == 0

fileinfo, serr := os.stat(path)

if serr != nil

if fileinfo.isdir()

if fileinfo.size() > int64(1<<30)

file, err := os.open(path)

if err != nil

defer file.close()

data := make(byte, fileinfo.size(), fileinfo.size())

_, rerr := file.read(data)

if rerr != nil

return string(data), nil

}//fileputcontents php函式file_put_contents 實現

func fileputcontents(path string, content string, ftype int) (int, error)

}} else

} file, err = os.openfile(path, os.o_rdwr|ftype, os.filemode(0666))

len, werr := file.writestring(content)

if werr != nil

err = file.close()

if err != nil

return len, nil

}

測試測試

php.fileputcontents("d:\\go\\ddd\\file_test.txt", "file_putcontents test", php.file_apend|php.file_create)

go lang 讀寫檔案操作

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

Golang 檔案讀寫操作

package main import fmt io log os path filepath strconv func main strfile strdir testfile.txt fmt.println file to open is strfile 開啟檔案,如果沒有,那麼建立,設定為讀寫...

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...