当前位置:网站首页>Go language foundation ----- 13 ----- file
Go language foundation ----- 13 ----- file
2022-07-03 07:37:00 【Mango sauce】
1 Document classification and why documents are needed
1.1 Document classification and why documents are needed
1) Device file :
The screen ( Standard output equipment ) fmt.Println() Write content from standard output device .
keyboard ( Standard input devices ) fmt.Scan() Read content from standard input device .2) Disk files , A file placed on a storage device :
1、 text file Open... In Notepad , Can see the content ( It's not a mess ).
2、 Binary Open... In Notepad , Can see the content ( It's garbled ).3) Why do you need files ?
1、 Memory power loss , Program end , The contents of memory disappear .
2、 Put files on disk , Program end , The files still exist .
2 Document common operation interface introduction and use
1、 create a file
Law 1: Recommended use
func Create(name string) (file *File, err Error)
Create a new file based on the filename provided , Return a file object , Default permissions are 0666 The file of , The returned file object is readable and writable .
Law 2:
func NewFile(fd uintptr, name string) *File
Create the corresponding file according to the file descriptor , Return a file object
2、 Open file
Law 1:
func Open(name string) (file *File, err Error)
This method opens a name called name The file of , But it's read-only , The internal implementation actually calls OpenFile.
Law 2: Recommended use
func OpenFile(name string, flag int, perm uint32) (file *File, err Error)
Open name as name The file of ,flag It's the way it's opened , read-only 、 Reading and writing, etc ,perm It's authority
3、 Writing documents
Law 1:
func (file *File) Write(b []byte) (n int, err Error)
write in byte Type of information to file
Law 2:
func (file *File) WriteAt(b []byte, off int64) (n int, err Error)
Start writing... At the specified location byte Type information
Law 3:
func (file *File) WriteString(s string) (ret int, err Error)
write in string Information to file
4、 Reading documents
Law 1:
func (file *File) Read(b []byte) (n int, err Error)
Read data to b in
Law 2:
func (file *File) ReadAt(b []byte, off int64) (n int, err Error)
from off Start reading data to b in
5、 Delete file
func Remove(name string) Error
Call this function to delete the filename name The file of
3 Use of standard equipment documents
Here is just a brief note .
package main
import (
"fmt"
"os"
)
func main() {
//os.Stdout.Close() // After closing , Unable to output
//fmt.Println("are u ok?") // To the standard output device ( The screen ) Write content
// 1. standard output
// Standard equipment documentation (os.Stdout), The default is on , Users can use
//os.Stdout
os.Stdout.WriteString("are u ok?\n")
//os.Stdin.Close() // After closing , Unable to input
// 2. The standard input
var a int
fmt.Println(" Please enter a: ")
fmt.Scan(&a) // Read content from standard input device , Put it in a in
fmt.Println("a = ", a)
}
4 WriteString Use
package main
import (
"fmt"
"os"
)
func WriteFile(path string) {
// 1. New file
f, err := os.Create(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// 2. After use , Need to close file
defer f.Close()
// 3. Write to the file
var buf string
for i := 0; i < 10; i++ {
//"i = 1\n", This string is stored in buf in
buf = fmt.Sprintf("i = %d\n", i)
//fmt.Println("buf = ", buf)
n, err := f.WriteString(buf)
if err != nil {
fmt.Println("err = ", err)
}
fmt.Println("n = ", n)
}
}
func main() {
path := "./demo.txt"
WriteFile(path)
}
Generate a demo.txt:
5 Read Use
package main
import (
"fmt"
"io"
"os"
)
func WriteFile(path string) {
f, err := os.Create(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// After use , Need to close file
defer f.Close()
var buf string
for i := 0; i < 10; i++ {
//"i = 1\n", This string is stored in buf in
buf = fmt.Sprintf("i = %d\n", i)
//fmt.Println("buf = ", buf)
n, err := f.WriteString(buf)
if err != nil {
fmt.Println("err = ", err)
}
fmt.Println("n = ", n)
}
}
func ReadFile(path string) {
f, err := os.Open(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// Close file
defer f.Close()
buf := make([]byte, 1024*2) //2k size
//n Represents the length of the content read from the file
n, err1 := f.Read(buf)
if err1 != nil && err1 != io.EOF {
// File error , At the same time, there is no end
fmt.Println("err1 = ", err1)
return
}
fmt.Println(string(buf[:n]))
}
func main() {
path := "./demo.txt"
// Write
//WriteFile(path)
// read
ReadFile(path)
}
Read the contents written above :
6 With the help of bufio Read content by line
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func WriteFile(path string) {
// Open file , New file
f, err := os.Create(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// After use , Need to close file
defer f.Close()
var buf string
for i := 0; i < 10; i++ {
//"i = 1\n", This string is stored in buf in
buf = fmt.Sprintf("i = %d\n", i)
//fmt.Println("buf = ", buf)
n, err := f.WriteString(buf)
if err != nil {
fmt.Println("err = ", err)
}
fmt.Println("n = ", n)
}
}
func ReadFile(path string) {
// Open file
f, err := os.Open(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// Close file
defer f.Close()
buf := make([]byte, 1024*2) //2k size
//n Represents the length of the content read from the file
n, err1 := f.Read(buf)
if err1 != nil && err1 != io.EOF {
// File error , At the same time, there is no end
fmt.Println("err1 = ", err1)
return
}
fmt.Println("buf = ", string(buf[:n]))
}
// Read one line at a time
func ReadFileLine(path string) {
// Open file
f, err := os.Open(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// Close file
defer f.Close()
// Create a new buffer , Put the content in the buffer first
r := bufio.NewReader(f)
for {
// encounter '\n' End read , But it will connect '\n' Itself will also read into . But not because there is \n And stop , This is very good .
buf, err := r.ReadBytes('\n')
if err != nil {
if err == io.EOF {
// The file is over
break
}
fmt.Println("err = ", err)
}
fmt.Printf("buf = #%s#\n", string(buf))
}
}
func main() {
path := "./demo.txt"
//WriteFile(path)
//ReadFile(path)
ReadFileLine(path)
}
take WriteString Read the contents of by line , But it will connect \n It will also read :
But not because there is \n And stop reading , For example, modify demo.txt:
You can see that you can also read \n.
7 Copy file cases
package main
import (
"fmt"
"io"
"os"
)
func main() {
list := os.Args // Get command line parameters
if len(list) != 3 {
fmt.Println("usage: xxx srcFile dstFile")
return
}
srcFileName := list[1]
drcFileName := list[2]
if srcFileName == drcFileName {
fmt.Println(" Source and destination file names cannot be the same ")
return
}
// Open source file in read-only mode
sF, err1 := os.Open(srcFileName)
if err1 != nil {
fmt.Println("err1 = ", err1)
return
}
// Create a new destination file
dF, err2 := os.Create(drcFileName)
if err2 != nil {
fmt.Println("err2 = ", err2)
return
}
// Operation completed , Need to close file
defer sF.Close()
defer dF.Close()
// Core processing , Read content from source file , Write to the destination file , Read as much as you write
buf := make([]byte, 4*1024) //4k Size temporary buffer
for {
n, err := sF.Read(buf) // Read content from source file
if err != nil {
if err == io.EOF{
// File read complete
break
}
fmt.Println("err = ", err)
}
// Write to the destination file , Read as much as you write
dF.Write(buf[:n])
}
}
First, generate the executable program :
# Enter the corresponding drive letter
d:
#cd Go to the corresponding directory
cd D:\xxx\xxx
#build Generate executable
go build test.go
# Finally, execute the copy command
test.exe demo.txt yyy.txt
yyy The content and content of demo.txt It's the same , picture 、 The copy of the video is no problem .
Be careful : Need to use cmd Go to build, Do not use bash, I tried. No , Can only cmd Go to build. Otherwise, the parameter loss will be reported when the copy command is executed .
边栏推荐
- Lucene hnsw merge optimization
- 项目经验分享:基于昇思MindSpore,使用DFCNN和CTC损失函数的声学模型实现
- Industrial resilience
- OSI knowledge sorting
- [mindspire paper presentation] summary of training skills in AAAI long tail problem
- FileInputStream and fileoutputstream
- IO stream system and FileReader, filewriter
- Lucene skip table
- 【LeetCode】2. Valid Parentheses·有效的括号
- How long is the fastest time you can develop data API? One minute is enough for me
猜你喜欢
随机推荐
研究显示乳腺癌细胞更容易在患者睡觉时进入血液
Why is data service the direction of the next generation data center?
Technical dry goods Shengsi mindspire operator parallel + heterogeneous parallel, enabling 32 card training 242 billion parameter model
Analysis of the problems of the 12th Blue Bridge Cup single chip microcomputer provincial competition
Vertx restful style web router
Vertx metric Prometheus monitoring indicators
为什么说数据服务化是下一代数据中台的方向?
Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
技术干货|关于AI Architecture未来的一些思考
Talk about floating
Analysis of the problems of the 7th Blue Bridge Cup single chip microcomputer provincial competition
IPv4 address
Circuit, packet and message exchange
Comparison of advantages and disadvantages between most complete SQL and NoSQL
Hisat2 - stringtie - deseq2 pipeline for bulk RNA seq
Robots protocol
Usage of requests module
截图工具Snipaste
基于RNA的新型癌症疗法介绍