Comparison of three file operations
ioutil
bufio
When the file is small (KB level), ioutil > bufio > os.
When the file size is relatively regular (MB level), the three are not much different, but bufio has already appeared again.
When the file is large (GB level), bufio > os > ioutil.
ioutil
read
//readfunc Ioutil_read() { file, _ := ("./") (string(file)) }
Write
//Writefunc Ioutil_write() { ("./",[]byte("aaaa\nbbb\ncccc\nLalala"),0777) }
read
// Waste of memory, solution, Baidu queryfile,_ := ("./") b,_:=(file) (string(b))
View directory information under the path
func Ioutil_ReadDir() { dir,_:=("./") for _,file := range dir{ (()) //File name (()) //File size (()) //Judge whether it is a directory (()) //View read and write permissions-rw-r--r-- (()) //File creation time } }
Create a temporary directory
// Create a temporary directory, starting with jeff, eg:jeff0123755func Ioutil_Tempdir() { path,_ := ("./","jeff") (path) //Return to the temporary directory path}
Create a temporary file
// Create a temporary file, starting with jeff, eg:jeff067576func Ioutil_file() { //Open the file in read and write mode and return the pointer path,_:=("./","jeff") (path) //Return pointer}
method
() //Create a file, if there is one, the file will be cleared() // Open the file read-only(file name,Open method,Open permissions) Write() //WriteRead() //Read
()
The OpenFile( ) function has three parameters
The first parameter indicates the path to open the file
The second parameter represents the mode, the common modes are
O_RDONLY (read-only mode),
O_WRONLY (write-only mode),
O_RDWR (readable and writable mode),
O_APPEND (Append mode).
The third parameter indicates permissions, value range (0-7)
It is expressed as follows:
0: No permissions
1: Execution permission (if it is executable, it can be run)
2: Write permission
3: Write permissions and execution permissions
4: Read permission
5: Read permissions and execution permissions
6: Read permissions and write permissions
7: Read permission, write permission, execution permission
fp,err := ("D:/",os.O_RDWR,6) if err!=nil { ("Failed to open the file") } ("hello") ([]byte("hello"),25) defer ()
Create a file
Before storing data to a file, create the file. A Create() function is provided in the GO language to create files specifically.
When creating a file, this function will first determine whether the file to be created exists. If it does not exist, it will be created. If it exists, the data already exists in the file will be cleared first.
At the same time, when the file is created successfully, the file will be opened by default, so you can write data directly to the file without performing the opening operation.
Steps to create a file:
(1) The functions that import the "os" package, create files, and read and write files are all in this package
(2) Specify the created file storage path and file name.
(3) Execute the Create( ) function to create a file
(4) Close the file
Specific code:
package main import ( "fmt" "os" ) func main() { //(File name) File name You can write absolute and relative paths //Return value File pointer Error message fp,err := ("./") if err!=nil{ //File creation failed /* 1. The path does not exist 2. File permissions 3. Program opens file limit */ ("File creation failed") return } //Read and write files defer () //Close the file //If the file is not closed, it will cause memory waste. The upper limit of the program's opening file is the program //() }
Three ways to write data
The first type -WriteString( ) function
WriteString( )The method returns two parameters by default,The first parameter,Refers to the length of the data written to the file,The second parameter records the error message WriteString( )The data written to the file by default is not wrapped.。If you want to change the line,The following method can be used: //\nNo line breaking reasons in windows text file\r\n Enter in linux\n("hello world\r\n") ("Sexy dealer dealer online")
After the file is opened, you can write data to the file, and you can use the WriteString( ) method.
//\Backslashes escape characters//You can use /forward slash instead of backslash when writing pathfp,err := ("D:/") if err!=nil{ //File creation failed /* 1. The path does not exist 2. File permissions 3. Program opens file limit */ ("File creation failed") return } //Write a file//\nNo line breaking reasons in windows text file\r\n Enter in linux\n("hello world\r\n") ("Sexy dealer dealer online") defer () //Close the file//If the file is not closed, it will cause memory waste. The upper limit of the program's opening file is the program//()
The second type -Write( ) function
It should be noted here that when writing data using the Write( ) function, the parameters are byte slices, so you need to convert the string into byte slices. This method also returns the length of the file data written to it.
fp,err := ("D:/") if err!=nil{ //File creation failed /* 1. The path does not exist 2. File permissions 3. Program opens file limit */ ("File creation failed") return } //Write operation//slice := []byte{'h','e','l','l','o'} //count,err1 := (slice) count,err1 := ([]byte("Sexy Lao Wang teaches online")) if err1!=nil { ("Write to file failed") return }else { (count) } defer ()
The third type - WriteAt( ) function
Write data at the specified location. In the following program, the return value of the Seek( ) function is stored in the variable n, and the value is the position at the end of the file. WriteAt( ) also returns the length of the data written.
fp,err := ("D:/") if err!=nil{ //File creation failed /* 1. The path does not exist 2. File permissions 3. Program opens file limit */ ("File creation failed") return } //Write operation//Get cursor flow position'//Get how many characters are there from the beginning to the end of the file//count,_:=(0,os.SEEK_END) count,_:=(0,) (count) //Write to the specified location([]byte("hello world"),count) ([]byte("hahaha"),0) ([]byte("Xiu'er"),19) defer ()
Read the file
Read File Read
If the file already exists and there is data, you can directly read the contents in the file.
The basic process of reading files is as follows:
(1) Open the file to be read
(2) Read the file
(3) Close the file
When writing data to a file, use Write, so when reading the data in the file, use Read.
The use of Read( ) function is as follows:
package main import ( "fmt" "io" "os" ) func main() { //Open the file fp, err := ("D:/") if err != nil { ("err=", err) return } buf := make([]byte, 1024*2) //2k size //n represents the length of reading content from the file n, err1 := (buf) if err1 != nil && err1 != { ("err1=", err1) return } ("buf=", string(buf[:n])) //Close the file defer () }
Open( ) is to open a file. The difference from OpenFile( ) is that Open( ) only has the permission to read.
When reading the content in a file using the Read( ) function, a slice type is needed. When defining the slice, the type is a character array. Save the content in the file in the slice. In addition to judging whether there is an error in it, it also needs to determine whether it is at the end of the file (the io package needs to be imported here).
The Read( ) function returns the length of data read from the file. Finally, output the file data stored in the slice. Note that the data read from the beginning to the entire data length, because it is possible that the data stored in the slice cannot reach the total length of the slice (it is also 2k during the slice, but the data read from the file may be only 1k).
Read by line
Above we read all the contents of the file and store them in a slice. We can also read only one line of data at a time.
This requires the use of the ReadBytes function in the bufio package. The details are as follows:
1: Open the file
fp, err := ("D:/") if err != nil { ("Failed to open the file", err) return }
2: Create a buffer
When reading data using the ReadBytes( ) function, a buffer needs to be used. The so-called buffer is the area where data is stored, that is, the data read from the file is first stored in the area, and then the data in the area is taken out and written to disk. The reason for providing a buffer is:
To alleviate the conflict between the speed mismatch between the CPU and the disk device. The file buffer is a certain space reserved in the memory area for temporarily storing file data during reading and writing.
//Create a file bufferr := (fp)
3: Loop to read the contents in the file until the end of the file.
for { //End reading after encountering '\n', but '\n' also read into buf,err := ('\n') ("buf = ",string(buf)) if err != nil { if err == { break } ("err=",err) } }
When using the ReadBytes( ) function, the passed parameter is ‘\n’, which means that it ends when it encounters ‘\n’, so a dead loop is used (one line of data is read every loop), and the entire loop is exited only when it reaches the end of the file. Finally, print out the read data, note that ReadBytes( ) returns a byte slice, so it must be converted into a string when printing.
4: Finally close the file
//Close the filedefer ()
Now that we have completed the operation of creating, reading, and saving data to the file, when operating on the file, we need to specify the path to the file.
There are two situations regarding the path:
First: Relative path. The so-called relative path refers to the path of a file relative to the application. For example: The file we used above is the same as the path of the executable file storage.
Second: Absolute path: refers to the fact that this file can be found directly on my computer through the given path. For example: D:\,
- We recommend that we use relative paths in development in the future
File operation cases
Copy the file, copy the existing file and rename it.
Basic ideas:
(1) Let the user enter the name of the file to be copied (source file) and the name of the destination file
(2) Create a target file
(3) Open the source file and read the contents in the file
(4) Write the content read from the source file to the destination file.
var srcFileName string var dstFileName string ("Please enter the source file name:") (&srcFileName) ("Please enter the destination file name:") (&dstFileName) if srcFileName == dstFileName { ("The source file and destination file name cannot be the same") return } //Open source file read-onlysF,err1 := (srcFileName) if err1 != nil { ("err1=",err1) return } // Create a new target filedF,err2 := (dstFileName) if err2 != nil{ ("err2=",err2) return } //The operation is completed and the file needs to be closeddefer () defer () //Core processing, reading content from source files, writing to destination files, reading as much as possiblebuf := make([]byte,4*1024)// 4k size temporary bufferfor{ n,err := (buf)//Read content from source files, read part of it each time if err != nil{ ("err=",err) if err == {//The file is finished reading break } } //Write to the destination file, read as much as you read (buf[:n]) }
The above is the detailed explanation of the GO file creation and read and write operation examples. For more information about GO file creation and read and write operation, please pay attention to my other related articles!