Go語言學習之os包中檔案相關的操作(The way to go)

來源:互聯網
上載者:User

標籤:hand   path   刪除檔案   letter   rmi   values   iss   als   remove   

生命不止,繼續 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 mainimport (    "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()}

Go語言學習之os包中檔案相關的操作(The way to go)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.