咖啡伴侶

          呆在上海
          posts - 163, comments - 156, trackbacks - 0, articles - 2

          Go語言文件操作

          Posted on 2013-08-02 10:43 oathleo 閱讀(276) 評論(0)  編輯  收藏 所屬分類: Golang

          寫程序離不了文件操作,這里總結下go語言文件操作。

          一、建立與打開

          建立文件函數:

          func Create(name string) (file *File, err Error)

          func NewFile(fd int, name string) *File

          具體見官網:http://golang.org/pkg/os/#Create

           

          打開文件函數:

          func Open(name string) (file *File, err Error)

          func OpenFile(name string, flag int, perm uint32) (file *File, err Error)

          具體見官網:http://golang.org/pkg/os/#Open

           

          二、寫文件

          寫文件函數:

          func (file *File) Write(b []byte) (n int, err Error)

          func (file *File) WriteAt(b []byte, off int64) (n int, err Error)

          func (file *File) WriteString(s string) (ret int, err Error)

          具體見官網:http://golang.org/pkg/os/#File.Write 

          寫文件示例代碼:

          package main import (         "os"         "fmt" ) func main() {         userFile := "test.txt"         fout,err := os.Create(userFile)         defer fout.Close()         if err != nil {                 fmt.Println(userFile,err)                 return         }         for i:= 0;i<10;i++ {                 fout.WriteString("Just a test!\r\n")                 fout.Write([]byte("Just a test!\r\n"))         } }

          三、讀文件

          讀文件函數:

          func (file *File) Read(b []byte) (n int, err Error)

          func (file *File) ReadAt(b []byte, off int64) (n int, err Error)

          具體見官網:http://golang.org/pkg/os/#File.Read

          讀文件示例代碼:

          package main import (         "os"         "fmt" ) func main() {         userFile := "test.txt"         fin,err := os.Open(userFile)         defer fin.Close()         if err != nil {                 fmt.Println(userFile,err)                 return         }         buf := make([]byte, 1024)         for{                 n, _ := fin.Read(buf)                 if 0 == n { break }                 os.Stdout.Write(buf[:n])         } }

          四、刪除文件

          函數:

          func Remove(name string) Error

          主站蜘蛛池模板: 天门市| 柘荣县| 钟祥市| 酉阳| 理塘县| 喀喇沁旗| 永川市| 哈密市| 扶余县| 绥芬河市| 湛江市| 龙门县| 上蔡县| 滨州市| 丹巴县| 治县。| 龙川县| 平潭县| 平顺县| 南宫市| 安康市| 荥阳市| 永丰县| 南涧| 舞钢市| 甘孜| 宜丰县| 阿巴嘎旗| 白水县| 桦南县| 兴业县| 旬阳县| 霍邱县| 桑植县| 尼玛县| 长阳| 深州市| 朝阳县| 石家庄市| 调兵山市| 海林市|