“This is the 23rd day of my participation in the August Challenge

This section describes the OS package structure

  • The OS package in the Go language standard library provides a platform-independent operating system interface
  • Designed to be UNIX-style, error handling is Go style, with failed calls returning error values rather than error codes. Often the error value contains more information
  • OS package and sub-package functions
-- OS package -- OS /exec package, responsible for executing external commands -- OS /signal access to input information -- OS /user Queries user accounts by name or IDCopy the code
  • The user structure is provided in OS/User to represent the operating system user
    • Uid user id
    • Gid INDICATES the ID of a group
    • The Username Username
    • Name Name of the owning group
    • HomeDir Folder path of the user
// User represents a user account.
type User struct {
	// Uid is the user ID.
	// On POSIX systems, this is a decimal number representing the uid.
	// On Windows, this is a security identifier (SID) in a string format.
	// On Plan 9, this is the contents of /dev/user.
	Uid string
	// Gid is the primary group ID.
	// On POSIX systems, this is a decimal number representing the gid.
	// On Windows, this is a SID in a string format.
	// On Plan 9, this is the contents of /dev/user.
	Gid string
	// Username is the login name.
	Username string
	// Name is the user's real or display name.
	// It might be blank.
	// On POSIX systems, this is the first (or only) entry in the GECOS field
	// list.
	// On Windows, this is the user's display name.
	// On Plan 9, this is the contents of /dev/user.
	Name string
	// HomeDir is the path to the user's home directory (if they have one).
	HomeDir string
}
Copy the code
  • Group in OS /user indicates the Group to which the user belongs
    • Gid group id
    • Name Group Name
// Group represents a grouping of users.
//
// On POSIX systems Gid contains a decimal number representing the group ID.
type Group struct {
	Gid  string // group ID
	Name string // group name
}
Copy the code
  • The entire OS /user package is relatively light, providing two error types and get the current user, find the user
type UnknownUserError
  func (e UnknownUserError) Error(a) string
type UnknownUserIdError
  func (e UnknownUserIdError) Error(a) string
type User
  func Current(a) (*User, error)
  func Lookup(username string) (*User, error)
  func LookupId(uid string) (*User, error)
Copy the code

Code sample

  • You can obtain the current user or obtain the user information after searching for the user
   // Get the current login user
   //u,_:=user.Current()
   /* Lookup(); /* Lookup(); /* Lookup()
   u, _ := user.Lookup(`LAPTOP-APM56\maishuren`)
   fmt.Println(u.Name)
   fmt.Println(u.Gid)
   fmt.Println(u.HomeDir)
   fmt.Println(u.Uid)
   fmt.Println(u.Username)
Copy the code

This section describes the OS package

  • Use the contents of the OS package for operating system files or directories
  • The File structure represents an operating system File (folder)
// File represents an open file descriptor.
type File struct {
	*file // os specific
}
Copy the code
// file is the real representation of *File.
// The extra level of indirection ensures that no clients of os
// can overwrite this data, which could cause the finalizer
// to close the wrong file descriptor.
type file struct {
	pfd     poll.FD
	name    string
	dirinfo *dirInfo // nil unless directory being read
}
Copy the code
  • All files in the OPERATING system have permission control, including files that can be read or written. In the OS package, FileMode indicates the file permission, which is essentially uint32 and can be provided in the form of constants
// A FileMode represents a file's mode and permission bits.
// The bits have the same definition on all systems, so that
// information about files can be moved from one system
// to another portably. Not all bits apply to all systems.
// The only required bit is ModeDir for directories.
type FileMode uint32
Copy the code
// The defined file mode bits are the most significant bits of the FileMode.
// The nine least-significant bits are the standard Unix rwxrwxrwx permissions.
// The values of these bits should be considered part of the public API and
// may be used in wire protocols or disk representations: they must not be
// changed, although new bits might be added.
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; Plan 9 only
	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
)
Copy the code
  • FIleInfo is an interface that represents information about a file
// A FileInfo describes a file and is returned by Stat and Lstat.
type FileInfo interface {
	Name() string       // base name of the file
	Size() int64        // length in bytes for regular files; system-dependent for others
	Mode() FileMode     // file mode bits
	ModTime() time.Time // modification time
	IsDir() bool        // abbreviation for Mode().IsDir()
	Sys() interface{}   // underlying data source (can return nil)
}
Copy the code

Resource path

  • Resource paths are classified into relative paths and absolute paths when obtaining system resources
  • Relative paths: In Go, relative paths are used for GOPATH, the root directory of the project
  • Absolute path: The root directory of a disk starts with a detailed description of the resource path

Code sample

  • The Go language standard library provides two ways to create folders
	/* The folder does not exist and the parent directory must exist in order to create */
	//error := os.Mkdir("D:/godir", os.ModeDir)
	//if error ! = nil {
	// fmt.Println(" folder creation failed ",error)
	//	return
	/ /}
	//fmt.Println(" folder created successfully ")


	/* If the folder already exists, no error is reported, keep the original folder if the parent directory does not exist help create */
	error := os.MkdirAll("D:/godir/a/b", os.ModeDir)
	iferror ! =nil {
		fmt.Println("Folder creation failed",error)
		return
	}
	fmt.Println("Folder created successfully")
Copy the code
  • Creating an empty file
	If the file already exists, an empty file will be created to overwrite the previous file */
	file, err := os.Create("D:/godir/test.txt")
	iferr ! =nil {
		fmt.Println("File creation failed,", err)
		return
	}
	fmt.Println("File created successfully",file.Name())
Copy the code
  • Rename a file or folder
	/* First argument: old folder name, the path must exist second argument: new folder name */
	err := os.Rename("D:/godir"."D:/godir1")
	iferr ! =nil {
		fmt.Println("Failed to rename folder,", err)
		return
	}
	fmt.Println("Folder renamed successfully")

	/* Renaming files is the same as renaming folders */
	err = os.Rename("D:/godir1/test.txt"."D:/godir1/test1.txt")
	iferr ! =nil {
		fmt.Println("Failed to rename file,", err)
		return
	}
	fmt.Println("File renamed successfully")
Copy the code
  • Get file (folder) information
	f, err := os.Open("D:/godir1/test1.txt")
	defer f.Close() // Close the file to free resources
	iferr ! =nil {
		fmt.Println("Failed to open file", err)
		return
	}
	fileInfo, err := f.Stat()
	iferr ! =nil {
		fmt.Println("Failed to obtain file information", err)
		return
	}
	fmt.Println(fileInfo.Name())    / / file name
	fmt.Println(fileInfo.IsDir())   Bool True indicates a folder; false indicates a file
	fmt.Println(fileInfo.Mode())    // File permissions
	fmt.Println(fileInfo.ModTime()) // Change the time
	fmt.Println(fileInfo.Size())    // File size
Copy the code
  • Delete files or folders
	/* The deleted content can only be a file or an empty folder and must exist */
	//err := os.Remove("D:/godir1/a")
	//if err ! = nil {
	// fmt.Println(" Failed to delete file ", err)
	//	return
	/ /}
	// FMT.Println(" delete succeeded ")

	/* Delete the folder as long as it exists. Delete files */ if the target folder is a file
	err := os.RemoveAll("D:/godir1/a.txt")
	iferr ! =nil {
		fmt.Println("Delete failed", err)
		return
	}
	fmt.Println("Deleted successfully")
Copy the code

The input stream

  • A stream is a link between an application and an external resource for data interaction

  • A stream is divided into input stream and output stream. Input and output are relative to the program. The external data passed into the program is called input, and vice versa is called output stream

  • An Input Stream is an I/O Stream

  • In the IO package of the Go language standard library, the Reader interface represents the input stream. As long as this interface is implemented, it belongs to the input stream

// Reader is the interface that wraps the basic Read method.
//
// Read reads up to len(p) bytes into p. It returns the number of bytes
// read (0 <= n <= len(p)) and any error encountered. Even if Read
// returns n < len(p), it may use all of p as scratch space during the call.
// If some data is available but not len(p) bytes, Read conventionally
// returns what is available instead of waiting for more.
//
// When Read encounters an error or end-of-file condition after
// successfully reading n > 0 bytes, it returns the number of
// bytes read. It may return the (non-nil) error from the same call
// or return the error (and n == 0) from a subsequent call.
// An instance of this general case is that a Reader returning
// a non-zero number of bytes at the end of the input stream may
// return either err == EOF or err == nil. The next Read should
// return 0, EOF.
//
// Callers should always process the n > 0 bytes returned before
// considering the error err. Doing so correctly handles I/O errors
// that happen after reading some bytes and also both of the
// allowed EOF behaviors.
//
// Implementations of Read are discouraged from returning a
// zero byte count with a nil error, except when len(p) == 0.
// Callers should treat a return of 0 and nil as indicating that
// nothing happened; in particular it does not indicate EOF.
//
// Implementations must not retain p.
type Reader interface {
	Read(p []byte) (n int, err error)
}
Copy the code

Code demo

  • You can create a string stream using NewReader under the Strings package
	r := strings.NewReader("Hello world")
	b := make([]byte, r.Size())// Create a byte slice to store data in the stream. Create a slice size according to the stream data size
	n, err := r.Read(b)// Read data from the stream into the slice
	iferr ! =nil {
		fmt.Println("Read failed,", err)
		return
	}
	fmt.Println("Read data length,", n)

	fmt.Println("Data in stream".string(b))// Enter the slice data as a string
Copy the code
  • The most common is file streaming, which reads data from an external file into a program
	f, err := os.Open("D:/go.txt")// Open the file
	defer f.Close()
	iferr ! =nil {
		fmt.Println("File read failed,", err)
		return
	}
	fileInfo, err := f.Stat()// Get file information
	iferr ! =nil {
		fmt.Println("Failed to get file information,", err)
		return
	}
	b := make([]byte, fileInfo.Size())// Create slices based on the size of the data in the file
	_, err = f.Read(b)// Read data into slices
	iferr ! =nil {
		fmt.Println("File stream reading failed :", err)
		return
	}
	fmt.Println("The contents of the document are :".string(b))// Enter the slice data as a string
Copy the code

The input stream

  • An input stream is a program that writes out data to an external resource
  • The output stream of the Go language standard library is the Writer interface
// Writer is the interface that wraps the basic Write method.
//
// Write writes len(p) bytes from p to the underlying data stream.
// It returns the number of bytes written from p (0 <= n <= len(p))
// and any error encountered that caused the write to stop early.
// Write must return a non-nil error if it returns n < len(p).
// Write must not modify the slice data, even temporarily.
//
// Implementations must not retain p.
type Writer interface {
	Write(p []byte) (n int, err error)
}
Copy the code

Code operation

  • Note: Do not use this when entering streamsos.Open()This is because the files obtained in this way are read-only
	fp := "D:/go.txt"
	/* The third argument means that the file permission bit 1 is always 0 in permissions bit 2 means that the file cannot be read, bit 1 means that the file can be read, bit 3 means that the file cannot be written, bit 1 means that the file can be written, bit 4 means that the file cannot be executed, 1(0001): read-write unavailable, can be executed 2(0010): writable, cannot be read, cannot be executed 3(0011): writable, cannot be read, can be executed 4(0100): 6(0110): read-write, cannot be executed. 7(0111): read-write, cannot be executed. 0666: The first 0 indicates that the number is octal. The first 6 indicates that the file owner has read and write permission, but no execute permission. The second 6 indicates that the same group of users has read and write permission, but no execute permission

	// The second parameter indicates that the file content is appended
	// The third parameter indicates the file permission when the file is created
	f, err := os.OpenFile(fp, os.O_APPEND, 0660)
	defer f.Close()
	iferr ! =nil {
		fmt.Println("File does not exist, create file")
		f, _ = os.Create(fp)
	}

	/* Recognize special characters \r\n newline \t indent */ in the content

	/* The Writer interface overridden with file objects. The argument is []byte */
	f.Write([]byte("Use Writer interface to write data \r\n"))

	/* Uses the stringWriter interface method, which takes a string and is more convenient */
	f.WriteString("Wrote \t a \r\n content 123")
	fmt.Println("Program execution completed")
Copy the code

Ioutil package

  • The ioutil package provides tool functions for reading and writing files. You can use these functions to quickly read and write files
  • The ioutil package provides fewer functions, but they are easy to use
func NopCloser(r io.Reader) io.ReadCloser
func ReadAll(r io.Reader) ([]byte, error)
func ReadFile(filename string) ([]byte, error)
func WriteFile(filename string, data []byte, perm os.FileMode) error
func ReadDir(dirname string) ([]os.FileInfo, error)
func TempDir(dir, prefix string) (name string, err error)
func TempFile(dir, prefix string) (f *os.File, err error)
Copy the code

Code demo

  • After opening the file, you can use ReadAll to ReadAll the contents of the file
	f, err := os.Open("D:/go.txt")
	defer f.Close()
	iferr ! =nil {
		fmt.Println(err)
		return
	}
	b, err := ioutil.ReadAll(f)
	iferr ! =nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Contents of file :\n".string(b))
Copy the code
  • You can also read the contents of the file directly
	b, err := ioutil.ReadFile("D:/go.txt")
	iferr ! =nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(b))
Copy the code
  • Writing a file is also very simple, using the WriteFile function directly, but the source code has stipulated that this file can only be writable, and not tail data
	err := ioutil.WriteFile("D:/abc.txt"And []byte("Content of 123123"), 0666)
	iferr ! =nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Data write succeeded")
Copy the code
  • It also provides functions to quickly get information about all the files in a folder
	fs,_:=ioutil.ReadDir("D:/")
	for _,n := range fs {
		fmt.Println(n.Name())
	}
Copy the code