您的位置:首页 > 编程语言 > Go语言

Go语言学习之os包中文件相关的操作(The way to go)

2017-04-24 14:39 351 查看
生命不止,继续 go go go !!!

今天跟大家分享学习的是os package,主要是介绍一些跟文件或文件夹相关的操作。

os包

Package os provides a platform-independent interface to operating system functionality.

The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers.

创建文件夹

创建一个文件夹,并指定权限:

func Mkdir(name string, perm FileMode) error


Mkdir creates a new directory with the specified name and permission bits

FileMode定义如下:

const (
// The single letters are the abbreviations
// used by the String method's formatting.
ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
ModeAppend                                     // a: append-only
ModeExclusive                                  // l: exclusive use
ModeTemporary                                  // T: temporary file (not backed up)
ModeSymlink                                    // L: symbolic link
ModeDevice                                     // D: device file
ModeNamedPipe                                  // p: named pipe (FIFO)
ModeSocket                                     // S: Unix domain socket
ModeSetuid                                     // u: setuid
ModeSetgid                                     // g: setgid
ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
ModeSticky                                     // t: sticky

// Mask for the type bits. For regular files, none will be set.
ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice

ModePerm FileMode = 0777 // Unix permission bits
)


创建一个文件夹:

os.Mkdir("test_go", 0777)


创建多级文件夹:

func MkdirAll(path string, perm FileMode) error


例如:

os.MkdirAll("test_go/go1/go2", 0777)


删除文件夹

删除就简单多了:

err := os.Remove("test_go")
if err != nil {
fmt.Println(err)
}
os.RemoveAll("test_go")


读取文件

可以使用os中的Open方法读取一文件:

file, err := os.Open("file.go") // For read access.
if err != nil {
log.Fatal(err)
}


还记得吗,我们之前介绍过ioutil包,里面也提到了如何打开一个文件:

dat, err := ioutil.ReadFile("file.go")
check(err)
fmt.Print(string(dat))


还有更狠的,指定文件权限和打开的方式:

f, err := os.OpenFile("file.go", os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}


创建文件

Create方法:

func Create(name string) (*File, error)


Create creates the named file with mode 0666 (before umask), truncating it if it already exists.

os.NewFile()函数原型是func NewFile(fd uintptr, name string) *File 第一个传入的是句柄,然后是文件名称,这个函数并不是真的创建了一个文件,是新建一个文件不保存,然后返回文件的指针

func NewFile(fd uintptr, name string) *File


二者的区别:

os.NewFile is a low level function that most people will never use directly. It takes an already existing file descriptor (system representation of a file) and converts it to an *os.File (Go’s representation).

读取文件

func (f *File) Read(b []byte) (n int, err error)


Read reads up to len(b) bytes from the File. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, io.EOF.

例子:

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


官方例子:

// Reading and writing files are basic tasks needed for
// many Go programs. First we'll look at some examples of
// reading files.

package main

import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)

// Reading files requires checking most calls for errors.
// This helper will streamline our error checks below.
func check(e error) {
if e != nil {
panic(e)
}
}

func main() {

// Perhaps the most basic file reading task is
// slurping a file's entire contents into memory.
dat, err := ioutil.ReadFile("/tmp/dat")
check(err)
fmt.Print(string(dat))

// You'll often want more control over how and what
// parts of a file are read. For these tasks, start
// by `Open`ing a file to obtain an `os.File` value.
f, err := os.Open("/tmp/dat")
check(err)

// Read some bytes from the beginning of the file.
// Allow up to 5 to be read but also note how many
// actually were read.
b1 := make([]byte, 5)
n1, err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1))

// You can also `Seek` to a known location in the file
// and `Read` from there.
o2, err := f.Seek(6, 0)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2))

// The `io` package provides some functions that may
// be helpful for file reading. For example, reads
// like the ones above can be more robustly
// implemented with `ReadAtLeast`.
o3, err := f.Seek(6, 0)
check(err)
b3 := make([]byte, 2)
n3, err := io.ReadAtLeast(f, b3, 2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))

// There is no built-in rewind, but `Seek(0, 0)`
// accomplishes this.
_, err = f.Seek(0, 0)
check(err)

// The `bufio` package implements a buffered
// reader that may be useful both for its efficiency
// with many small reads and because of the additional
// reading methods it provides.
r4 := bufio.NewReader(f)
b4, err := r4.Peek(5)
check(err)
fmt.Printf("5 bytes: %s\n", string(b4))

// Close the file when you're done (usually this would
// be scheduled immediately after `Open`ing with
// `defer`).
f.Close()

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: