go語言 檔案讀寫

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

檔案讀寫相關的函數在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()}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.