preface

File operation almost all programming languages will deal with the problem, and Golang provides a lot of file operation support, today to systematically comb through, several commonly used file read and write forms.

First of all, we haveGolang websiteTo findOS document

There are a number of file/folder operations that can be found in the Index location, and here’s how to use them

File operations

Create file:

If the Create file does not exist, Create the file using mode 0666. If the file exists, it will be cleared

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

Open the file

Open Opens the named file for reading. If successful, it can be read using the methods on the return file. The pattern of the associated file descriptor is O_RDONLY. If there is an error, it will be of type * PathError.

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

OpenFile opens a named file with the specified flag (O_RDONLY, etc.). If the file does not exist and the O_CREATE flag is passed, the file is created using the pattern PERm (before umask).

func OpenFile(name string, flag int, perm FileMode) (*File, error)

Write files

WriteFile writes data to a named file. If the file does not exist, create it with perm permission

func WriteFile(name string, data []byte, perm FileMode) error

Read the file:

Read Reads up to len (b) bytes from a file. It returns the number of bytes read and any errors encountered. At the end of the file, Read returns 0, io.eof.

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

Delete the file

Remove Deletes named files or (empty) directories. If there is an error, it will be of type * PathError.

os.Remove(filename)

Deletes the folder and all the subdirectories and files it contains

RemoveAll RemoveAll Deletes a path and all its descendants. RemoveAll returns nil if the path does not exist (no errors)

os.RemoveAll(dir)

Check whether the file exists

The Stat method returns the file description IsNotExist to verify that the error is known to report that the file or directory does not exist

func FileIsExisted(filename string) bool {
	existed := true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		existed = false
	}
	return existed
}
Copy the code

Copy files using os.read () and os.write ()

func CopyFile3(src, des string, bufSize int) (written int64, err error) {
    if bufSize <= 0 {
        bufSize = 1*1024*1024   //1M
    }
    buf := make([]byte, bufSize)
 
    srcFile, err := os.Open(src)
    iferr ! =nil {
        return 0, err
    }
    defer srcFile.Close()
 
    // Obtain the permission for the source file
    fi, _ := srcFile.Stat()
    perm := fi.Mode()
 
    desFile, err := os.OpenFile(des, os.O_CREATE|os.O_RDWR|os.O_TRUNC, perm)
    iferr ! =nil {
        return 0, err
    }
    defer desFile.Close()
 
    count := 0
    for {
        n, err := srcFile.Read(buf)
        iferr ! =nil&& err ! = io.EOF {return 0, err
        }
 
        if n == 0 {
            break
        }
 
        ifwn, err := desFile.Write(buf[:n]); err ! =nil {
            return 0, err
        } else {
            count += wn
        }
    }
 
    return int64(count), nil
}
Copy the code