Go language file I/O operations

  1. Master the routine operation of files
  2. Master ioutil use
  3. Master the use of bufio packages

I/O, also known as Input/Output, can also be understood as read and write operations.

1.1 Definition of documents

A file is an ordered geometry of related data. Files usually reside on external media (such as disks) and are called into memory only when they are used.

A file must have: 1. File path. 2. File name and suffix.

1.2 the FileInfo interface

File information includes file name, file size, modification permission, and modification time

The FileInfo interface of Go language is as follows

type FileInfo interface {
	name() string
	size() int64
	mode() os.FileMode
	modTime() time.Time
	isDir() bool
	sys() interface{}
}
Copy the code

File paths are classified into absolute paths and relative paths.

Thisgo. go Relative path:… /goDemo/thisGo.go

Prints file information

package main import ( "fmt" "os" ) func printMes(path string) { fileInfo,err:=os.Stat(path) if err! =nil{fmt.println ("err", err.error ())}else{fmt.printf (" Data type :%T\n",fileInfo) fmt.println (" filename :", fileinfo.name ()) FMT.Println(" whether directory :", fileinfo.isdir ()) FMT.Println(" file Size :", fileinfo.size ()) FMT.Println(" file permission :", fileinfo.mode ()) Println(" last modified date :", fileinfo.modtime ())}} func main() {// Absolute path:="D:/c/test.txt" printMes(path)} /* TXT Directory: false File size :0 File permission: -RW-RW-RW-Last modified date: 2021-07-16 10:43:08.9098702 +0800 CST */Copy the code

File permissions are printed out in 10 characters. Files have three basic permissions: r(read), W (write), and x(execute).

1.3 File Path

Methods related to the file path

Package main import (" FMT ""path" "path/filepath") func main() {// Absolute path filepath :="D:/c/test.txt" // relative path FMT.Println(filepath.IsAbs(filepath)) // Check whether it is an absolute path fmt.Println(path.Join(filePath,".." )) FMT. Println (path. Join (" D: / c/test. TXT ", filePath)) / / stitching relative path} / * true. < nil > D: D/c: / c/test. TXT/D: / c/test. TXT * /Copy the code

1.4 General File operations

Create a directory. If the directory exists, the creation fails

1, OS. MKdirAll ()

2, OS. MKdirAll ()

Package main import (" FMT "" OS") func main() {fileP:="D:/c/" err:= os.mkdir (fileP, os.modeperm) if err! = nil {FMT. Println (" err: "err, Error ())} else {FMT. Println (" file to create successful")} fileP = "D: / c/c / / create the directory err=os.Mkdir(fileP,os.ModePerm) if err! Println("err:", err.error ())}else{fmt.println (" file created successfully ")} fileP2:="D:/test/ ABC /xy" err=os.MkdirAll(fileP2,os.ModePerm) if err! =nil{fmt.println ("err", err.error ())}else{fmt.println (fileP2," document created successfully ")}} /* Err: mkdir D:/c/: Cannot create a file when that file already exists. D:/test/ ABC /xy file created successfully */Copy the code

1.5 Creating a File

Os.create (fileName) // fileName is the path and name of the file

Package main import (" FMT "" OS") func main() {fileName:="./bcd.txt" // Relative path to Create file file1,err:= os.create (fileName)  if err! =nil{fmt.println ("err:", err.error ())}else{fmt.printf ("%s created successfully %v\n",fileName,file1)}}Copy the code

1.6 Opening and closing the file

  1. FileName fileName
  2. Mode: file opening mode
  3. Perm, file permissions. To create a file that does not exist, you need to specify the permission.

package main import ( "fmt" "os" ) func main() { fileName:="./abc.txt" file2,err:=os.Open(fileName) if err! =nil{fmt.println ("err", err.error ())}else{fmt.printf ("%s open successfully! %v\n",fileName,file2)} fileName1:="./ rgp.txt" File does not exist, it automatically create a new file file4, err: = OS. The OpenFile (fileName1, OS O_RDWR | OS. O_CREATE, OS. ModePerm) if err! =nil{fmt.println ("err:", err.error ())}else{fmt.printf ("%s open successfully! %v\n",fileName1,file4)} file2.close () file4.close ()} &{0xC000100780}./rgb.txt opened successfully! &{0xc000100a00} */Copy the code

1.7 Deleting a File

There are two ways to delete a file:

package main import ( "fmt" "os" ) func main() { fileName:="./bcd" err:=os.Remove(fileName) if err! =nil{fmt.println (err)}else{fmt.printf ("%s delete succeeded! \n",fileName)} ero:= os.removeall (fileName) // Remove its path and all its children fmt.println (ero) if ero! =nil{fmt.println (ero)}else{fmt.printf ("%s removed successfully!!" /* The system cannot find The file specified. <nil>./ The system cannot find The file specified. * /Copy the code

As you can see, removing a non-empty directory using the os.remove () method fails

1.8 Reading and Writing Files and Copying Files

package main import ( "fmt" "io" "os" ) func main() { filePath:="./abc.txt" file,err:=os.Open(filePath) if err! =nil{FMT.Println(" error opening file!" , err)} else {bs: = make (byte [], 1024 * 8102 8 * 8) n: = 1 for {n, err = file. Read (bs) if n = = 0 | | err. = = IO EOF {FMT. Println (" Read the end of file ") Println(string(bs[:n]))}} file.close ()} /* 123456897 1213455478 End of reading file */Copy the code

1.9 Writing a File

Steps to write a file:

  1. Open or create a file
  2. Written to the file
  3. Close the file
  4. **file.Close()**

package main import ( "fmt" "os" ) func main() { file,err:=os.OpenFile("./abc.txt",os.O_RDWR|os.O_CREATE,os.ModePerm) defer file.Close() if err! Println(" open file Error ", err.error ())}else{n,err:= file.write ([] byte("this is A B C D")) if err! =nil{FMT.Println(" writer-exception!" , err.error ())}else{fmt.println (" Write OK! ") ,n)}} n,err:= file.writeString (" WriteString! ") ) if err! = nil {FMT. Println (" abnormal written to the file: "err. Error ())} else {FMT. Println (" write OK:", n)}} / * * /Copy the code

This write deletes information inside the file

1.10 Copying Files

The Go language provides the copyFile() method to copy files.

package main import ( "fmt" "io" "os" ) func copyFile(srcFile,destFile string)(int64,error) { file1,err:=os.Open(srcFile) if err! =nil{ return 0,err } file2,err:=os.OpenFile(destFile,os.O_RDWR|os.O_CREATE,os.ModePerm) if err! =nil{return 0,err} defer file1.close () defer file2.close () return io.copy (file2,file1)} func main() {// Relative path of source file DestFile :="./xxx.txt" Total,err:=copyFile(srcFile,destFile) if err! =nil{fmt.println (err.error ())}else{fmt.println (" Copy done! ") ,total)}} /* Copy complete! 27 * /Copy the code