Life goes on and on go Go go!!!
Today, we share with you the OS package, which is mainly about files or folders related to the operation.
OS Package
Package OS provides a platform-independent interface to operating system functionality.
The design is unix-like, although the error handling is go-like; Failing calls return values of type error rather than error numbers.
Create a folder
Create a folder and specify the permissions:
funcstring, perm FileMode) error
Mkdir creates a new directory with the specified name and permission bits
FileMode is defined as follows:
Const(// The single letters is the abbreviations //used by the String method ' s formatting.Modedir FileMode =1<<( +-1-Iota)//D:is a directoryModeappend//A:append-onlyModeexclusive//l:exclusive useModetemporary//T:temporary file (not backed up)Modesymlink//L:symbolic linkModedevice//D:device fileModenamedpipe//P:named pipe (FIFO)Modesocket//S:unix domain socketModesetuid//U:setuidModesetgid//G:setgidModechardevice//C:unix character device, when Modedevice is setModesticky//T:sticky //Mask for the type bits. For regular files, none would be set.Modetype = Modedir | Modesymlink | Modenamedpipe | Modesocket | Modedevice Modeperm FileMode =0777 //Unix permission bits)
Create a folder:
os.Mkdir("test_go", 0777)
To create a multilevel folder:
funcstring, perm FileMode) error
For example:
os.MkdirAll("test_go/go1/go2", 0777)
Delete a folder
It's a lot easier to delete:
err := os.Remove("test_go") ifnil { fmt.Println(err) } os.RemoveAll("test_go")
Read File
You can use the Open method in the OS to read a file:
file, err := os.Open("file.go"// For read access.ifnil { log.Fatal(err)}
Remember, we introduced the Ioutil package before, and it also mentions how to open a file:
dat, err := ioutil.ReadFile("file.go")check(err)fmt.Print(string(dat))
And more ruthless, specify file permissions and how to open it:
f, err := os.OpenFile("file.go", os.O_RDWR|os.O_CREATE, 0755)ifnil { log.Fatal(err)}ifnil { log.Fatal(err)}
Create a file
Create method:
funcstring) (*File, error)
Create creates the named file with mode 0666 (before umask), truncating it if it already exists.
Os. The NewFile () function prototype is the Func NewFile (fd uintptr, name string) *file the first pass-through is a handle, then the file name, and this function does not really create a file, is a new file is not saved, and then returns a pointer to the file
funcuintptrstring) *File
The difference between the two:
Os. NewFile is a low level function, which most people would never use directly. It takes an already existing file descriptor (System representation of a file) and converts it to an *os. File (Go ' s representation).
Read file
func (f *File) Read(b []byteint, err error)
Read reads up to Len (b) bytes from the File. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, Io. Eof.
Example:
"test_go.txt" fl, err := os.Open(userFile) ifnil { fmt.Println(userFile, err) return } defer fl.Close() make([]byte, 1024) for { n, _ := fl.Read(buf) if 0 == n { break } os.Stdout.Write(buf[:n]) }
Official examples:
//Reading and writing files is basic tasks needed for//Many Go programs. First we ' ll look at some examples of//reading files. PackageMainImport("Bufio" "FMT" "IO" "Io/ioutil" "OS")//Reading files requires checking most calls for errors.//This helper would streamline our error checks below.funcCheck (e error) {ifE! =Nil{Panic(e)}}funcMain () {//Perhaps the most basic file reading task is //slurping a file ' s entire contents into memory.DAT, err: = Ioutil. ReadFile ("/tmp/dat") Check (err) fmt. Print (string(DAT))//You'll often want more control over how and what //Parts of a file is read. For these tasks, start //by ' Open ' ing a file to obtain an ' OS. File ' value.F, err: = OS. Open ("/tmp/dat") Check (ERR)//Read Some bytes from the beginning of the file. /Allow up to 5 to being read but also note how many //actually were read.B1: = Make([]byte,5) n1, Err: = F.read (B1) Check (err) fmt. Printf ("%d bytes:%s\n", N1,string(B1))//can also ' Seek ' to a known location in the file //And ' Read ' from there.O2, err: = F.seek(6,0) Check (err) B2: = Make([]byte,2) N2, Err: = F.read (b2) Check (err) fmt. Printf ("%d bytes @%d:%s\n", N2, O2,string(B2))//The ' IO ' package provides some functions //is helpful for file reading. For example, reads //Like the ones above can is more robustly //implemented with ' Readatleast '.O3, err: = F.seek(6,0) Check (ERR) B3: = Make([]byte,2) N3, err: = Io. Readatleast (F, B3,2) Check (err) fmt. Printf ("%d bytes @%d:%s\n", N3, O3,string(b3))//There is no built-in rewind, but ' Seek (0, 0) ' //accomplishes this._, Err = F.seek(0,0) Check (ERR)//The ' Bufio ' package implements a buffered //Reader that May is useful both for its efficiency //With many small reads and because of the additional //Reading Methods it provides.R4: = Bufio. Newreader (f) B4, err: = R4. Peek(5) Check (err) fmt. Printf ("5 bytes:%s\n",string(B4))//Close The file when you ' re done (usually this would //Be scheduled immediately after ' Open ' ing with //' defer ').F.close ()}
The file-related action in the Go Language learning OS package (the path to go)