Reading operations of Go files
os package and bufio package
Go standard libraryos
Package provides us with many functions that operate files, such asOpen(name)
Open the file,Create(name)
Create files and other functions, corresponding to them isbufio
Bag,os
The package operates directly on the disk, andbufio
The package is a buffered operation, and you don’t have to operate the disk every time.
and
-
Open(name string) (*File, error)
passfile nameorFile path + file nameOpen a file in the form of , this file can only be used for reading operations, and if the file does not exist, it will be returned
PathError
。- Parameters
name
forfile nameorFile path + file name。 - Return value
*File
For oneFile
The pointer type of the structure, through which pointers can read and write files, etc.
- Parameters
Return value
`error` is an error that occurs during the process of opening the file.
OpenFile(name string, flag int, perm FileMode) (*File, error)
By specifyingfile nameorFile path + file nameOpen a file with three parameters: file operation mode, and file permissions, and then read and write operations on the file.
- Parameters
name
forfile nameorFile path + file name。 - Parameters
flag
To specify the file operation mode, optional values areO_RDONLY
→ Read-only operation,O_WRONLY
→ Write-only operation,O_RDWR
→ Read and write operations,O_APPEND
→ Append data to the file during writing,O_CREATE
→ If it does not exist, create a new file, etc. - Parameters
perm
Parameters represent the file's pattern and permissions, for example0666
For read and write permissions. If you don't understand the number corresponding to file permissions, you can learn it. - Return value
*File
For oneFile
The pointer type of the structure, through which pointers can read and write files, etc. - Return value
error
An error occurred during the process of opening the file.
(b []byte) (n int, err error)
Read andb
bytes of equal length and stored inb
in.
- Parameters
b
is a slice array that specifies the read length and store byte data. - Return value
n
The length of the bytes read. - Return value
error
An error occurred during the reading of bytes.
Read file operation
import ( "fmt" "os" ) func main() { file, err := ("") if err != nil { (err) return } defer () data := make([]byte, 11) count, err := (data) if err != nil { return } ("Byte Data:", data) // [72 101 108 108 111 32 119 111 114 108 100] ("String data:", string(data)) // Hello world ("Length of the retrieved bytes:", count) // 11 }
Execution results:
Byte data: [72 101 108 108 111 32 119 111 114 108 100]
String data: Hello world
The length of the obtained bytes: 11
- First pass
Open
Function openFile, use
file
Variable reception, default to readable mode; - Then create a length of
11
byte slice, then passfile
Variable methodRead
The read length is11
byte data.("")
Equivalent to("", os.O_RDONLY, 0)
。 - Finally, print the read data. After the file operation is completed, the file needs to be closed.
()
。
and
Read files, it is recommended to useand
, reduce disk operation.
-
NewReader(rd ) *Reader
Get a buffered oneReader
Pointer variable, the default buffer size is4096
byte. The data can be read through variables.- Parameters
rd
As an interface, all data type variables that implement this interface can be used as parameters, such as the above mentionedFile
。 - Return value
*Reader
forReader
Pointer to the structure, the buffer data can be read through the pointer.
- Parameters
-
ReadString(delim byte) (string, error)
Read data until the first time you encounter a separatordelim
So far. An error occurs during reading process will returnEOF
error message.- Parameters
delim
It is a delimiter, and it will terminate every time it is read. - The first return value is the read content, including the separator.
- The second return value is the error message generated during the reading process.
- Parameters
Read file operation
The content of the file is:
Hello world
Hello Golang
Hello Gopher
import ( "bufio" "fmt" "io" "os" "strings" ) func main() { file, err := ("", os.O_RDONLY, 0) if err != nil { (err) return } defer () reader := (file) for { if lineData, err := ('\n'); err != nil { if err == { // Because the line break is used as the separator, if there is no line break on the last line, then when the error is returned, the data may be read. Therefore, determine whether the data has been read. if len(lineData) > 0 { (lineData) } break } } else { ((lineData, "\n")) } } }
Execution results:
Hello World
Hello Golang
Hello Gopher
- First pass
OpenFile
Function openFile, use
file
Variable reception, specified as readable mode; - Then pass
NewReader
The function creates a buffer and reads bytes of default length into the buffer; - Then pass
Reader
Structural methodReadString
,by\n
As a separator, read the data by line and then print the data. - One of the points of attention is that because the newline is used as the separator. If there is no newline on the last line, then return
When there is an error, data may also be read, so you need to determine whether the data has been read.
Go file write operation
、、
-
(b []byte) (n int, err error)
Directly operate the disk to write data into the file, and the writing unit is bytes.
-
b
Parameters: The written data, type of byte slice. - Return value
n
: The number of bytes written. - Return value
err
: Errors generated during writing data.
-
-
(s string) (n int, err error)
Directly operate the disk to write data into the specified file, and the writing unit is a string.
-
s
Parameters: written string data. - Return value
n
: The number of bytes written. - Return value
err
: Errors generated during writing data.
-
-
(b []byte, off int64) (n int, err error)
From the specified location
off
Write data into the file in sequence, and if there is data on a certain offset, it will be overwritten.-
b
Parameters: The written data, type of byte slice. -
off
Parameters: Offset, starting from this position to write data. - Return value
n
: The number of bytes written. - Return value
err
: Errors generated during writing data.
-
File writing operation
import ( "fmt" "os" ) func main() { file, err := ("", os.O_CREATE, 0) if err != nil { (err) return } defer () count, err := ([]byte{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\n'}) if err != nil { return } ("Written %d byte\n", count) count, err = ("Hello Golang") if err != nil { return } ("Written string of length %d\n", count) count, err = ([]byte{'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'}, 0) if err != nil { return } ("Written %d byte\n", count) }
- Open first
File, specified mode is
os.O_CREATE
, if the file does not exist, it will be created automatically; - Then pass
Write
Methods are written into the file in the form of charactersHello World\n
content;
Then passWriteString
Methods are written into the file as stringsHello Golang
Content; the content in the file is as follows:
Hello World
Hello Golang
Finally passedWriteAt
Method, specify the slave offset as0
Start writing data at the locationxxxxxxxxxxx
,because0
There is data at the location afterwards, so the original data is overwritten. The contents of the last file are:
xxxxxxxxxxx
Hello Golang
-
(offset int64, whence int)
Set the offset to set the current read or write relative to the beginning or the current position or the end position.
offset
。-
offset
Parameters: The offset to be set. -
whence
: The flag of the offset starts to be set relative to which position, the optional value is0
→ the beginning position,1
→ Current location,2
→ The end position.
-
application
import ( "fmt" "os" ) func main() { file, err := ("", os.O_CREATE, 0) if err != nil { (err) return } defer () _, err = ("G0lang") if err != nil { return } _, err = (1, 0) if err != nil { (err) return } _, err = ([]byte{'o'}) if err != nil { (err) return } }
- Open
File, specified mode is
os.O_CREATE
, if the file does not exist, it will be created automatically; - use
WriteString
Method to write to the fileG0lang
string; - At this time, I found that the second character was wrong.
0
It should be changed too
;The offset at this time points to the tail; useSeek
Method moves the offset to the second position and then writes the charactero
, because there is data at the current location0
,thereforeo
Will cover0
;
、、
If you need to execute the write operation to a file multiple times, it is recommended to usebufio
The insideWriter
To operate the structure, it will open a buffer, the default size is4096
byte. Before the data is flushed to disk, the written data will be temporarily saved to the buffer.
-
NewWriter(w ) *Writer
Open a default value as
4096
Buffer of bytes is used to temporarily store the data content written to the file, and returns aWriter
Pointer variable of structure-
w
Parameter: Type isWriter
Interface, the data type variables that implement this interface can be used as parameters, for exampleFile
。 - Return value
*Writer
:oneWriter
Pointer variable of the structure, through which data can be written into the buffer.
-
-
(s string) (int, error)
How to write content into the buffer.
- Parameters
s
is the written string. - The first return value is the number of bytes written.
- The second return value is an error generated during the writing process of data.
- Parameters
-
() error
Write all cached data to disk.
- The return value is an error generated during the process of writing data to disk.
File writing operation
import ( "bufio" "fmt" "os" ) func main() { file, err := ("", os.O_CREATE, 0) if err != nil { (err) return } defer () writer := (file) _, err = ("Hello World\n") if err != nil { (err) return } _, err = ("Hello Golang\n") if err != nil { (err) return } _, err = ("Hello Gopher\n") if err != nil { (err) return } () }
- Open first
File, specified mode is
os.O_CREATE
, if the file does not exist, it will be created automatically; - Then use
NewWriter
Function gets oneWriter
Pointer variables of structurewriter
; - Then pass
writer
ofWriteString
Method saves the content to the buffer; - Last call
Flush
Method, write all cached data to disk.
summary
Recommended file reading operationsbufio
The one in the bagNewReader
Functions andReader
Structural methodReadString
, can reduce disk operation and read data efficiently.
Recommended file writing operations、
、
, use them instead of the writing method in the File structure, so that the disk can be operated frequently and the writing efficiency can be improved.
The above is the comprehensive detailed content of Go file reading and writing operations. For more information about Go file reading and writing operations, please pay attention to my other related articles!