How to create a file directory in Golang
In this issue, the editor will bring you about how to create a file directory in Golang. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Creation and deletion of file directories
Package mainimport ("fmt"os") func main () {/ / create directories and permissions os.Mkdir (". / benben", 0777) / / create multi-level directories and set permissions os.MkdirAll (". / benben/test" 0777) / / delete directory err:=os.Remove (". / benben") if erratic directory nil {fmt.Println (err)} / / delete multi-level directory os.RemoveAll (". / benben")}
Creation of files
Package mainimport ("os"fmt") func main () {/ / file creation. Create creates a file based on the file name passed in. The default permission is 0666 file,err:=os.Create ("a.txt") if erratic permission nil {fmt.Println (err)} defer file.Close ()}
File opening and closing functions related to file opening and closing are demonstrated in the file read and write examples.
There are several ways to read and write files: method one: using os.Open () and ioutil.ReadAll () methods.
Package mainfunc main () {/ / Open file file,err:=os.Open ("a.txt") if err! = nil {fmt.Println (err)} / / close defer file.Close () / / File read mode 1, return a file handle through os.Open Then use it to read body,err:=ioutil.ReadAll (file) if err! = nil {fmt.Println (err)} fmt.Println (string (body))}
Method 2: use the ioutil.ReadFile () method to realize the read operation.
Package mainfunc main () {body,err:=ioutil.ReadFile ("a.txt") if erratic roomnil {fmt.Println (err)} fmt.Println (string (body))}
The ReadFile function directly divides the three steps in Mode 1 together. Here is the specific code for the implementation.
Func ReadFile (filename string) ([] byte,error) {/ / Open (filename) if erratically closed nil {return nil,err} / / delayed closing of the file defer f.Close () / / sets the number of bytes to read the file var n int64 / / Stat () method returns the information structure FileInfo if fi,err:=f.Stat () that describes the specified file Err==nil {if size:=fi.Size (); size