Golang file Operations

Source: Internet
Author: User

File read

os.File

Encapsulates file-related operations

Type File
File represents an open files object

func Create(name string) (file *File, err error)
    • Create takes mode 0666 (anyone can read and write, not execute) creates a file named name.
    • If the file already exists it truncates it (to an empty file).
    • If successful, the returned file object is available for I/O, and the corresponding file descriptor has O_RDWR mode.
    • If an error occurs, the error underlying type is *patherror.
func Open(name string) (file *File, err error)

Open opens a file for reading. If the operation succeeds, the method of the returned file object can be used to read the data;
The corresponding file descriptor has o_rdonly mode. If an error occurs, the error underlying type is *patherror.

func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
    • OpenFile is a more general file open function, and most callers apply open or create instead of this function.
    • It opens a file of the specified name using the specified options (such as o_rdonly, etc.), the specified pattern (such as 0666, and so on).
    • If the operation succeeds, the returned file object is available for I/O.
    • If an error occurs, the error underlying type is *patherror.
func NewFile(fd uintptr, name string) *File

NewFile creating a file using the given UNIX file descriptor and name

func Pipe() (r *File, w *File, err error)

Pipe returns a pair of associated file objects. Reading from R will return the data written to W.
This function returns two file objects and possible errors.

func (f *File) Name() string

The name method returns the file names (provided to methods such as Open/create).

func (f *File) Stat() (fi FileInfo, err errror)

Stat returns the FileInfo type value of the description file F. If there is an error, the wrong base type is *patherror.

func (f *File) Fd() uintptr

FD returns the Unix file descriptor of the integer type corresponding to the file F.

func (f *File) Chdir() error

ChDir the current working directory is modified to f,f must be a directory. If an error occurs, the wrong underlying type is *patherror

func (f *File) Chmod(mode FileMode) error

chmod Modify the mode of the file. If an error occurs, the wrong underlying type is *patherror

func (f *File) Chown(uid, git int) error

Chown Modify the user ID and group ID of the file. If there is an error, the wrong base type is *patherror.

func (f *File) Readdir(n int) (fi []FileInfo, err error)
    • Readdir reads the contents of the directory F and returns an N-member []fileinfo, which is returned by Lstat, in the directory order.
    • The next call to this function returns information about the last call to the remaining unread content.
    • If the N>0,readdir function returns a slice of up to N members.
    • At this point, if Readdir returns an empty slice, it returns a non-nil error stating the reason.
    • If the end of the directory F is reached, the return value err will be IO. Eof.
    • If n<=0, the Readdir function returns a slice of the fileinfo composition of all the file objects remaining in the directory.
    • At this point, if the Readdir call succeeds (all content is read until the end), it returns the slice and nil error values.
    • If an error is encountered before reaching the end, it returns a slice of the fileinfo that was previously successfully read and the error.
func (f *File) Readdirnames(n int) (names []string, err error)
    • Readdir reads the contents of the directory F and returns an N-member []string, whose slice member is the name of the file object in the directory, in the directory order.
    • The next call to this function returns information about the last call to the remaining unread content.
    • If the N>0,readdir function returns a slice of up to N members. At this point, if Readdir returns an empty slice, it returns a non-nil error stating the reason.
    • If the end of the directory F is reached, the return value err will not IO. Eof.
    • If the N<=0,readdir function returns a slice of the name of all the file objects remaining in the directory. At this point, if the Readdir call succeeds (all content is read until the end), it returns the slice and nil error values.
    • If an error is encountered before reaching the end, the slice and the error are returned from the name that was successfully read before.
func (f *File) Truncate(size int64) error

Truncate changes the size of the file, it does not change the current position of I/O. If you truncate the file, the extra portion is discarded. If an error occurs, the error underlying type is *patherror.

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

The Read method reads up to Len (b) byte data from F and writes B. It returns the number of bytes read and any errors that may be encountered. The file termination flag is read 0 bytes and the return value err is IO. Eof.

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

ReadAt reads Len (b) byte data from the specified location (relative to the start of the file) and writes B.
It returns the number of bytes read and any errors that may be encountered. When N<len (b), this method always returns an error, and if it is due to the end of the file, the return value err will be IO. Eof.

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

Write writes Len (b) Byte data to the file. It returns the number of bytes written and any errors that may be encountered. If the return value is n! = Len (b), this method returns a non-nil error.

func (f *File) WriteString(s string) (ret int, err error)

WriteString similar to write, but accepts a string parameter.

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

Writeat writes Len (b) byte data at the specified position relative to the start of the file. It returns the number of bytes written and any errors that may be encountered. If the return value is n! = Len (b), this method returns a non-nil error.

func (f *File) Seek(offset int64, whence int) (ret int64,err error)

Seek sets the next read/write position. Offset is the relative offset, and whence determines the relative position: 0 is relative to the beginning of the file, 1 is relative to the current position, and 2 is relative to the end of the file.
It returns the new offset (relative to the beginning) and possible errors.

func (f *File) Sync() (err error)

Sync submits the current contents of the file for stable storage. In general, this means that the most recently written data from the file system is flushed to the hard disk in a steady-memory copy.

func (f *File) Close() error

Close closes the file F so that the file cannot be used for read-write. It returns the error that may have occurred.

Read/write Parameters

File Open mode:

const (    O_RDONLY int = syscall.O_RDONLY    // 只读模式打开文件    O_WRONLY int = syscall.O_WRONLY    // 只写模式打开文件    O_RDWR   int = syscal.O_RDWR       // 读写模式打开文件    O_APPEND int = syscall.O_APPEND    // 写操作时将数据附加到文件尾部    O_CREATE int = syscall.O_CREAT     // 如果不存在将创建一个新文件    O_EXCL   int = syscall.O_EXCL      // 打开文件用于同步I/O    O_SYNC   int = syscall.O_SYNC      // 打开文件用于同步I/O    O_TRUNC  int = syscall.O_TRUNC     // 如果可能,打开时清空文件)

Read example

Os. Open | | Os. OpenFile

pacakge mainimport (    "bufio"    "fmt"    "os")func main() {    // file, err := os.Open("/tmp/test")    file, err := os.OpenFile("/tmp/test",os.O_CREATE|os.O_WRONLY,0666)    if err != nil {        fmt.Println("Open file error:",err)        return    }    defer file.Close()    // 关闭文件        reader := bufio.NewReader(file)   //带缓冲区的读写    for {        str, err := reader.ReadString('\n')  //循环读取一行        if err != nil {            fmt.Println("read string failed, err: ",err)            return        }        fmt.Println("read string is %s: ",str)    }}

ReadLine

Read the contents of the file in one row

package mainimport (    "bufio"    "fmt"    "io"    "os")func main() {    file, err := os.Open("/tmp/test.log")    if err != nil {        fmt.Println(err)        return    }    defer file.Close()    reader := bufio.NewReader(file)    var line []byte    for {        data, prefix, err := reader.ReadLine()        if err == io.EOF {            break        }        line = append(line, data...)        if !prefix {            fmt.Printf("data:%s\n",string(line))            line = line[:]        }    }}

Read the entire file example

The "Io/ioutil" package implements the ability to read the entire file

package mainimport (    "fmt"    "os"    "io/ioutil")func main() {    fileName := "/tmp/test"    file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)    if err != nil {        fmt.Println("Open file error: ",err)        return    }    defer file.Close()    buf, err := ioutil.ReadAll(file)    // buf, err := ioutil.ReadFile(fileName)    if err != nil {        fmt.Fprintf(os.Stderr, "File Error: %s\n",err)        return    }    fmt.Printf("%s\n",string(buf))}

Reading compressed Files

The "compress/*" package implements the compressed file function
"Compress/gzip" package enables the reading and writing of gzip compressed files

package mainimport (    "bufio"    "compress/gzip"    "fmt"    "os")func main() {    fileName := "/tmp/test.log.gz"    var r *bufio.Reader    fi, err := os.Open(fileName)    if err != nil {        fmt.Println("error",err)        os.Exit(1)    }        fz, err := gzip.NewReader(fi)    if err != nil {        fmt.Println("error",err)        return    }        r = bufio.NewReader(fz)    for {        line, err := r.ReadString('\n')        if err != nil {            fmt.Println("Done reading file")            return        }        fmt.Println(line)    }}

File Write

File. WriteString | | File. Write

package mainimport (    "fmt"    "os")func main() {    fileName := "/tmp/test_write"        file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0644)    if err != nil {        fmt.Println("error",err)        os.Exit(1)    }    defer file.Close()    fileString := "Today very happy."    file.Seek(0,2)  // 最后增加    file.WriteString(fileString)    // file.Write([]byte(fileString))}

Bufio. Writer.writestring

With buffered writes, the data in the buffer is then written to the underlying IO. Writer interface (Flush method)

package mainimport (    "bufio"    "fmt"    "os")func main() {    fileName := "/tmp/test_write"    file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0755)    if err != nil {        fmt.Println("error",err)        os.Exit(1)    }    defer file.Close()        fileWrite := bufio.NewWriter(file)    fileString := "good.\n"    for i := 0; i < 10; i++ {        fileWrite.WriteString(fileString)    }    fileWrite.Flush()}

Copy files

Copy from one file to another

package mainimport (    "fmt"    "io"    "os")func CopyFile(dstName, srcName string) (writeen int64,err error) {    src, err := os.Open(dstName)    if err != nil {        fmt.Println(err)        return    }    defer src.Close()        dst, err := os.OpenFile(srcName, os.O_CREATE|os.O_WRONLY, 0644)    if err != nil {        fmt.Println(err)        return    }    defer dst.Close()    return io.Copy(dst, src)}func main() {    CopyFile("/tmp/test","/tmp/test_copy1")    fmt.Println("copy done.")}

Determine if a file or folder exists

func PathExists(path string) (bool, error) {    /*    判断文件或目录是否存在    如果返回的错误为nil,说明文件或目录存在    如果返回的错误类型使用os.IsNotExits()判断为true,说明文件或文件夹不存在    如果返回的错误为其它类型,则不确定是否存在    */    _, err := os.Stat(path)    if err == nil {        return true,nil    }    if os.InNotExist(err) {        return false,nil    }    return false, err}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.