這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
檔案讀寫相關的函數在os包中,因此需要先匯入os包。
主要有以下幾個函數
func Create(name string) (file *File, err error) 直接通過紋面建立檔案 func NewFile(fd uintptr, name string) *File func Open(name string) (file *File, err error) 以唯讀方式開啟一個存在的檔案,開啟就可以讀取了。 func OpenFile(name string, flag int, perm FileMode) (file *File, err error) func Pipe() (r *File, w *File, err error) 管道 func (f *File) Chdir() error 改變當前的工作目錄 func (f *File) Chmod(mode FileMode) error 改變許可權 func (f *File) Chown(uid, gid int) error 改變所有者 func (f *File) Close() error 關閉檔案 func (f *File) Fd() uintptr 返迴文件控制代碼 func (f *File) Name() string 返迴文件名 func (f *File) Read(b []byte) (n int, err error) 讀取檔案 func (f *File) ReadAt(b []byte, off int64) (n int, err error) 從off開始讀取檔案 func (f *File) Readdir(n int) (fi []FileInfo, err error) 讀取檔案目錄返回n個fileinfo func (f *File) Readdirnames(n int) (names []string, err error) 讀取檔案目錄返回n個檔案名稱 func (f *File) Seek(offset int64, whence int) (ret int64, err error) 設定讀寫檔案的位移量,whence為0表示相對於檔案的開始處,1表示相對於當前的位置,2表示相對於檔案結尾。他返回位移量。如果有錯誤返回錯誤 func (f *File) Stat() (fi FileInfo, err error) 返回當前檔案fileinfo結構體 func (f *File) Sync() (err error) 把當前內容持久化,一般就是馬上寫入到磁碟 func (f *File) Truncate(size int64) error 改變當前檔案的大小,他不改變當前檔案讀寫的位移量 func (f *File) Write(b []byte) (n int, err error) 寫入內容 func (f *File) WriteAt(b []byte, off int64) (n int, err error) 在offset位置寫入內容 func (f *File) WriteString(s string) (ret int, err error) 寫入字元
一個簡單例子
import ("fmt""os")func writeFile() {file1, err := os.Create("test.txt")defer file1.Close()if err != nil {fmt.Println(file1, err)return}file1.WriteString("hello world")}func readFile() {file, err := os.Open("test.txt")defer file.Close()if err != nil {fmt.Println(file, err)}r_buf := make([]byte, 1024)for {n, _ := file.Read(r_buf)if n == 0 {break}fmt.Println(string(r_buf[0:n]))}}func main() {writeFile()readFile()}