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.

FileInfo interface

The FileInfo interface defines methods related to File information.

Type FileInfo interface {Name() string // base Name of the file file Name. TXT Size() int64 // File Size, Bytes 12540 Mode() FileMode // File permission -rw-RW-rw-modtime () time. time // Change time 2018-04-13 16:30:53 +0800 CST IsDir() bool // Sys() interface{} // Base data source interface (can return nil)}COPYCopy the code

Second, the 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:

There are two ways to represent file permissions in Linux, namely "symbolic representation" and "octal representation". (1) Symbol representation: -- -- -- -- -- -- -- -- -- -- type owner 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) such as: -rwxr-xr-x (2) octal representation: r -- > 004 w -- > 002 x -- > 001 -- > 000 0755 0777 0555 0444 0666COPYCopy the code

Third, open the mode

File opening mode:

O_RDONLY int = syscall.O_RDONLY // Open file in read-only mode O_WRONLY int = syscall.O_WRONLY // Open file in write-only mode O_RDWR int = O_RDWR // Open the file in read/write mode O_APPEND int = syscall.O_APPEND // Append data to the end of the file during write operations O_CREATE int = syscall.O_CREAT // O_EXCL int = syscall.O_EXCL // use with O_CREATE, File must not exist O_SYNC int = syscall.O_SYNC // Open file for I/O synchronization O_TRUNC int = syscall.O_TRUNC // Clear file when opened if possible)COPYCopy the code

4. File operation

Type File //File represents an open File object. Func Create(name string) (file * file, err error) //Create creates a file named name using mode 0666 (read-write by anyone, not executable) and truncates the 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) Most callers use Open or Create instead of this function. 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. //NewFile creates 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. A read from R returns data written to W. This function returns two file objects and possible errors. Func (f *File) Name() string //Name Returns the Name of the File (provided to methods such as Open/Create). Func (f *File) Stat() (fi FileInfo, err Error) //Stat Returns the FileInfo type value describing File f. If an error occurs, the underlying error type is *PathError. Func (f *File) Fd() uintptr //Fd Returns a Unix File descriptor of the integer type corresponding to File f. Func (f *File) Chdir() 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() 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 that is returned by Lstat. Use 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. Use 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, which does not change the current I/O position. If you truncate the file, the excess is discarded. If an error occurs, the underlying error type is *PathError. COPYCopy the code

Five, sample code

File information: FileInfo

Package main import (" OS "" FMT") func main() {/* FileInfo: File information interface Name(), file Name Size(), file Size, bytes IsDir(), whether directory ModTime(), modification time Mode(), Permissions * / the fileInfo, err: = OS. Stat ("/Users/ruby/Documents/pro/a/aa. TXT ") if err! Println("err :",err) return} fmt.printf ("%T\n",fileInfo) // File Name fmt.println (fileinfo.name ()) // File size Fmt.println (fileinfo.size ()) // Whether the directory is fmt.println (fileinfo.isdir ()) //IsDirectory // Change time fmt.println (fileinfo.modtime ()) / / permission FMT. Println (the fileInfo. Mode ()) / / rw - r - r -} COPYCopy the code

Running results:

File operation example:

Package main import (" FMT ""path/filepath" "path" "OS ") func main() {/* File operation: 1 Path: relative path: relative ab. TXT absolute path relative to the current project: absolute/Users/ruby/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. Remove files or directories with caution: Remove files and empty directories with caution os.remove (), Remove all */ //1. FileName1: path = "/ Users/ruby/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/ruby/go/ SRC /l_file/bb.txt FMT.Println(" Get parent directory: ",path.Join(fileName1,"..") )) / / 2. Create a directory / / err: = OS. The Mkdir ("/Users/ruby/Documents/pro/a/bb ", OS. ModePerm) / / if err! = nil {/ / FMT. Println (" err: "err) / / return / /} / / FMT Println (" folder to create success." ) //err :=os.MkdirAll("/Users/ruby/Documents/pro/a/cc/dd/ee",os.ModePerm) //if err ! = nil {/ / FMT. Println (" err: "err) / / return / /} / / FMT Println (" multi-layer folder to create a successful") / / 3. Create file :Create creates a file named name using pattern 0666 (readable and non-executable by anyone), If the file already exists it will truncate (empty files) / / file1, err: = OS. The Create ("/Users/ruby/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.) File does not exist to create a file, you need to specify the permissions * / / / file4, err: = OS. The OpenFile (fileName1, OS O_RDONLY | OS. O_WRONLY, OS. ModePerm) / / if err! = nil {/ / FMT. Println (" err: "err) / / return / /} / / FMT Println (file4) / / 5 closed files, / / file4 Close () / / 6. Delete files or folders: / / delete files / / err: = OS. Remove ("/Users/ruby/Documents/pro/a/aa. TXT ") / / if err! = nil {/ / FMT. Println (" err: "err) / / return / /} / / FMT Println (" delete files. Success." ) / / delete the directory err: = OS RemoveAll ("/a/Users/ruby/Documents/pro/cc ") if err! = nil{fmt.Println("err:",err) return} fmt.Println(" Directory deleted successfully." )}Copy the code