这个仍是在个人博客首发的,可是我感受人流量过小,咱们写博客的目的不只是记录咱们再用的时候遇到的问题,是为了更好的让你们在之后的学习和开发中也用到~~为go语言的宣传尽本身一点微薄的力量
今天咱们讲golang标准库的os包type File struct{},仍是废话少说直接上代码html
import ( "fmt" "os" "reflect" ) func main() { f, _ := os.Create("widuu_2.go") defer f.Close() fmt.Println(reflect.ValueOf(f).Type()) //*os.File }
这个函数的原理实际上是这样的OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) O_RDWR也就是说用读写的权限,O_CREATE而后文件存在忽略,不存在建立它,O_TRUNC文件存在截取长度为0,这就解释了为何咱们明明有这个文件,我擦,建立以后哭了~啥都没有了~~用的时候需谨慎,先判断文件是否存在~git
import ( "fmt" "os" ) func main() { f, _ := os.OpenFile("10.go", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) defer f.Close() fmt.Println(f.Stat()) }
这个就是上边的Create()只不过权限是0777以及下边的操做等大部分用到OpenFile()github
import ( "fmt" "os" "reflect" ) func main() { f, _ := os.Open("1.go") defer f.Close() }
import ( "fmt" "os" ) func main() { f, _ := os.Stat("1.go") fmt.Println(f.Size()) }
import ( "fmt" "os" ) func main() { f, _ := os.Open("1.go") fmt.Println(f.Fd()) //个人平台句柄是228 }
import ( "fmt" "os" ) func main() { r, w, _ := os.Pipe() fmt.Println(r, w) //&{0xc08402e120} &{0xc08402e180} }
import ( "fmt" "os" ) func main() { f, _ := os.Open("ini.go") defer f.Close() f1 := os.NewFile(f.Fd(), "ceshi.go") //输如ini.go的句柄 defer f1.Close() fd, _ := f1.Stat() fmt.Println(fd.ModTime()) //返回的是ini.go的建立时间2013-11-27 09:11:50.2793737 +0800 CST }
import ( "fmt" "os" ) func main() { dir, _ := os.Getwd() fmt.Println(dir) f, _ := os.Open("views") err := f.Chdir() if err != nil { fmt.Println(err) } dir1, _ := os.Getwd() fmt.Println(dir1) }
今天也就到这里,明天咱们继续哈~~~golang
博客首发在http://www.widuu.com/archives/01/921.html,你们能够在个人博客找前5个os包的讲解,天天一点了解golang
github的地址:https://github.com/widuu/gopkg编程