Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

File operation (IO, ioutil, bufio)

First, the File class is in the OS package and encapsulates the underlying file descriptor and related information, as well as the Read and Write implementations.

The FileInfo interface

The FileInfo interface defines methods related to File information.

type FileInfo interface {
	Name() string       // base name of the file name. The extension of aa. TXT
	Size() int64        // File size 12540 bytes
	Mode() FileMode     // File permissions -rw-rw-rw-
	ModTime() time.Time // Modify time 2018-04-13 16:30:53 +0800 CST
	IsDir() bool        // Whether folder
	Sys() interface{}   // Base data source interface (can return nil)
}
Copy the code
permissions

As for the operation permission perm, it needs to be specified only when creating a file. It can be set to 0 when no new file needs to be created. Although the GO language gives perm permissions a lot of constants, it is customary to use numbers such as 0666.

Permission control:

Linux under2Representation of file permissions, namely "symbolic representation" and "octal representation". (1) symbol: - --- --- ---typeOwner group others file permissions are that the distribution of read write executable corresponding r w x if without a permission, use - instead of d (- file directory | connection symbol), for example: - rwxr-xr-x mto (2) octal notation: r -- >004W - >002X - >001-- - >000

0755
0777
0555
0444
0666
Copy the code
Open mode

File opening mode:

const (
    O_RDONLY int = syscall.O_RDONLY // Open the file in read-only mode
    O_WRONLY int = syscall.O_WRONLY // Open the file in write only mode
    O_RDWR   int = syscall.O_RDWR   // Open the file in read-write mode
    O_APPEND int = syscall.O_APPEND // Write to append data to the end of the file
    O_CREATE int = syscall.O_CREAT  // A new file will be created if it does not exist
    O_EXCL   int = syscall.O_EXCL   // To be used with O_CREATE, the file must not exist
    O_SYNC   int = syscall.O_SYNC   // Open a file to synchronize I/O
    O_TRUNC  int = syscall.O_TRUNC  // If possible, empty the file when opened
)
Copy the code
The File operations
type File
//File represents an open File object.

func Create(name string) (file *File, err error)
//Create creates a file named name using pattern 0666 (read-write by anyone, not executable) and truncates it (empty file) if it already exists. If successful, the returned file object can be used for I/O; The corresponding file descriptor has the O_RDWR pattern. If an error occurs, the underlying error 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 the O_RDONLY mode. If an error occurs, the underlying error type is *PathError.

func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
OpenFile is a more general file-opening function. Most callers use Open or Create instead. It opens the named file with the specified option (O_RDONLY, etc.) and the specified mode (0666, etc.). If the operation succeeds, the returned file object can be used for I/O. If an error occurs, the underlying error type is *PathError.

func NewFile(fd uintptr, name string) *File
//NewFile creates a file with the given Unix file descriptor and name.

func Pipe(a) (r *File, w *File, err error)
//Pipe returns a pair of associated file objects. A read from R returns data written to W. This function returns two file objects and possible errors.

func (f *File) Name(a) string
The //Name method returns the Name of the file (provided to methods such as Open/Create).

func (f *File) Stat(a) (fi FileInfo, err error)
//Stat Returns a FileInfo value describing file f. If an error occurs, the underlying error type is *PathError.

func (f *File) Fd(a) uintptr
//Fd returns a Unix file descriptor of type integer corresponding to file f.

func (f *File) Chdir(a) error
//Chdir changes the current working directory to f, which must be a directory. If an error occurs, the underlying error type is *PathError.

func (f *File) Chmod(mode FileMode) error
//Chmod changes the file mode. If an error occurs, the underlying error type is *PathError.

func (f *File) Chown(uid, gid int) error
//Chown Changes the user ID and group ID of the file. If an error occurs, the underlying error type is *PathError.

func (f *File) Close(a) error
//Close Closes file f so that the file cannot be read or written. It returns possible errors.


func (f *File) Readdir(n int) (fi []FileInfo, err error)
//Readdir reads the contents of directory f and returns a []FileInfo with n members returned by Lstat in directory order. The next call to this function returns information about what was left unread from the previous call. If n>0, the Readdir function returns a slice with at most n members. At this point, if Readdir returns an empty slice, it returns a non-nil error saying why. If the end of directory f is reached, the return value of err will be io.eof. If n<=0, the Readdir function returns a FileInfo slice of all the remaining file objects in the directory. At this point, if the Readdir call succeeds (reading everything up to the end), it returns the wrong values for the slice and nil. If an error is encountered before the end is reached, the slice of the previously successfully read FileInfo and the error are returned.

func (f *File) Readdirnames(n int) (names []string, err error)
//Readdir reads the contents of directory f and returns a []string with n members. The sliced members are the names of the file objects in the directory, in directory order. The next call to this function returns information about what was left unread from the previous call. If n>0, the Readdir function returns a slice with at most n members. At this point, if Readdir returns an empty slice, it returns a non-nil error saying why. If the end of directory f is reached, the return value of err will be io.eof. If n<=0, the Readdir function returns a slice of the names of all the remaining file objects in the directory. At this point, if the Readdir call succeeds (reading everything up to the end), it returns the wrong values for the slice and nil. If an error is encountered before the end is reached, a slice of the previously successfully read names and the error are returned.

func (f *File) Truncate(size int64) error
Truncate changes the file size. It does not change the current position of the I/O. If you truncate the file, the excess is discarded. If an error occurs, the underlying error type is *PathError.
Copy the code
The sample code

File information: FileInfo

package main

import (
	"os"
	"fmt"
)

func main(a) {
	/* FileInfo: file information interface Name(), file Name Size(), file Size, bytes IsDir(), whether it is a directory ModTime(), modification time Mode(), permission */
	fileInfo,err :=  os.Stat("/Users/zzm/Documents/pro/a/aa.txt")
	iferr ! =nil{
		fmt.Println("err :",err)
		return
	}
	fmt.Printf("%T\n",fileInfo)
	/ / file name
	fmt.Println(fileInfo.Name())
	// File size
	fmt.Println(fileInfo.Size())
	// Is a directory
	fmt.Println(fileInfo.IsDir()) //IsDirectory
	// Change the time
	fmt.Println(fileInfo.ModTime())
	/ / permission
	fmt.Println(fileInfo.Mode()) //-rw-r--r--
}
Copy the code

File operation example:

package main

import (
	"fmt"
	"path/filepath"
	"path"
	"os"
)

func main(a) {
	/ * file operations: 1. The path: relative path: relative ab. TXT absolute path relative to the current project: absolute/Users/ZZM/Documents/pro/a/aa. TXT. Current directory.. Create a folder. If the folder exists, the creation fails. Os.mkdir () creates a layer of os.mkdirall (). Create creates a file named name, truncates it if it already exists (empty file) os.create (), creates file 4. OpenFile(filename) os.OpenFile(filename,mode,perm) 5 Close file: The link between a program and a file is broken. File.close () 5. Delete files or directories: use with caution, use with caution, use again with caution os.remove (), delete files and empty directories os.removeall (), and delete all */
	 / / 1. Path
	 fileName1:="/Users/zzm/Documents/pro/a/aa.txt"
	 fileName2:="bb.txt"
	 fmt.Println(filepath.IsAbs(fileName1)) //true
	 fmt.Println(filepath.IsAbs(fileName2)) //false
	 fmt.Println(filepath.Abs(fileName1))
	 fmt.Println(filepath.Abs(fileName2)) // /Users/zzm/go/src/l_file/bb.txt

	 fmt.Println("Get parent directory:",path.Join(fileName1,".."))

	 2. Create a directory
	 //err := os.Mkdir("/Users/zzm/Documents/pro/a/bb",os.ModePerm)
	 //if err ! = nil{
	 //	fmt.Println("err:",err)
	 //	return
	 / /}
	 //fmt.Println(" Folder created successfully." )
	 //err :=os.MkdirAll("/Users/zzm/Documents/pro/a/cc/dd/ee",os.ModePerm)
	 //if err ! = nil{
	 //	fmt.Println("err:",err)
	 //	return
	 / /}
	 //fmt.Println(" multilayer folder created successfully ")

	 //3. Create a file :Create creates a file named name using mode 0666 (anyone can read and write, not execute) and truncates it if it already exists (empty file)
	 //file1,err :=os.Create("/Users/zzm/Documents/pro/a/ab.txt")
	 //if err ! = nil{
	 / / FMT. Println (" err: "err)
	 //	return
	 / /}
	 //fmt.Println(file1)

	 //file2,err := os.create (fileName2)// Create a file with a relative path that is referenced to the current project
	 //if err ! = nil{
	 //	fmt.Println("err :",err)
	 //	return
	 / /}
	 //fmt.Println(file2)

	 //4. Open file:
	 //file3,err := os.Open(fileName1) // Read-only
	 //if err ! = nil{
	 //	fmt.Println("err:",err)
	 //	return
	 / /}
	 //fmt.Println(file3)
	/* First argument: file name; second argument: Const (// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified. O_RDONLY int = syscall.O_RDONLY // open the file read-only. O_WRONLY int = syscall.O_WRONLY  // open the file write-only. O_RDWR int = syscall.O_RDWR // open the file read-write. // The remaining values may be or'ed in to control behavior. O_APPEND int = syscall.O_APPEND // append data to the file when writing. O_CREATE int = syscall.O_CREAT // create a new file if none exists. O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist. O_SYNC int = syscall.O_SYNC // open for synchronous I/O. O_TRUNC int = syscall.O_TRUNC // truncate Regular writable file when opened. Regular writable file when opened
	 //file4,err := os.OpenFile(fileName1,os.O_RDONLY|os.O_WRONLY,os.ModePerm)
	 //if err ! = nil{
	 //	fmt.Println("err:",err)
	 //	return
	 / /}
	 //fmt.Println(file4)

	 // close the file,
	 //file4.Close()

	 //6. Delete files or folders:
	 // Delete files
	//err := os.Remove("/Users/zzm/Documents/pro/a/aa.txt")
	//if err ! = nil{
	//	fmt.Println("err:",err)
	//	return
	/ /}
	//fmt.Println(" File deleted successfully... ") )
	// Delete the directory
	err :=  os.RemoveAll("/Users/zzm/Documents/pro/a/cc")
	iferr ! =nil{
		fmt.Println("err:",err)
		return
	}
	fmt.Println("Directory deletion succeeded.")}Copy the code