举例详解Go语言中os库的常用函数用法

2020-01-28 11:58:24王旭

 if err != nil {
  fmt.Println(err)
 }
 for i, name := range names {
  fmt.Printf("filename %d: %sn", i, name)
 }
}

(f *File).Seek()这个函数大家一看就懂了,就是偏移指针的地址,函数的原型是func (f *File) Seek(offset int64, whence int) (ret int64, err error) 其中offset是文件指针的位置 whence为0时代表相对文件开始的位置,1代表相对当前位置,2代表相对文件结尾的位置 ret返回的是现在指针的位置

import (
 "fmt"
 "os"
)

func main() {
 b := make([]byte, 10)
 f, _ := os.Open("1.go")
 defer f.Close()
 f.Seek(1, 0)    //相当于开始位置偏移1
 n, _ := f.Read(b)
 fmt.Println(string(b[:n]))  //原字符package 输出ackage
}

(f *File) Write像文件中写入内容,函数原型func (f *File) Write(b []byte) (n int, err error)返回的是n写入的字节数

import (
 "fmt"
 "os"
)

func main() {
 f, _ := os.OpenFile("1.go", os.O_RDWR|os.O_APPEND, 0755) //以追加和读写的方式去打开文件
 n, _ := f.Write([]byte("helloword"))                     //我们写入hellword
 fmt.Println(n)                                           //打印写入的字节数
 b := make([]byte, 20)
 f.Seek(0, 0)            //指针返回到0
 data, _ := f.Read(b)
 fmt.Println(string(b[:data]))        //输出了packagehelloword
}

(f *File) WriteAt()在偏移位置多少的地方写入,函数原型是func (f *File) WriteAt(b []byte, off int64) (n int, err error)返回值是一样的

import (
 "fmt"
 "os"
)

func main() {
 f, _ := os.OpenFile("1.go", os.O_RDWR, os.ModePerm)
 f.WriteAt([]byte("widuu"), 10) //在偏移10的地方写入
 b := make([]byte, 20)
 d, _ := f.ReadAt(b, 10)    //偏移10的地方开始读取
 fmt.Println(string(b[:d])) //widuudhellowordhello
}

(f *File).WriteString()这个很简单了,写入字符串函数原型func (f *File) WriteString(s string) (ret int, err error)返回值一样的了

import (
 "fmt"
 "os"
)

func main() {
 f, _ := os.OpenFile("2.go", os.O_RDWR, os.ModePerm)
 n, _ := f.WriteString("hello word widuu") //写入字符串