当前位置:网站首页>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 .
边栏推荐
- PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
- Reconnaissance et détection d'images - Notes
- Robots protocol
- 技术干货|关于AI Architecture未来的一些思考
- The concept of C language pointer
- Some experiences of Arduino soft serial port communication
- lucene scorer
- Paper learning -- Study on the similarity of water level time series of Xingzi station in Poyang Lake
- Qtip2 solves the problem of too many texts
- HarmonyOS第三次培训笔记
猜你喜欢
Common methods of file class
技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer
Introduction of buffer flow
[Development Notes] cloud app control on device based on smart cloud 4G adapter gc211
不出网上线CS的各种姿势
IO stream system and FileReader, filewriter
Understanding of class
Hnsw introduction and some reference articles in lucene9
技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验
UA camouflage, get and post in requests carry parameters to obtain JSON format content
随机推荐
Chapter VI - Containers
Talk about floating
Sent by mqtt client server of vertx
PAT甲级 1032 Sharing
Lombok cooperates with @slf4j and logback to realize logging
Robots protocol
Leetcode 198: 打家劫舍
基于RNA的新型癌症疗法介绍
Topic | synchronous asynchronous
【MySQL 11】怎么解决MySQL 8.0.18 大小写敏感问题
【LeetCode】2. Valid Parentheses·有效的括号
VMware network mode - bridge, host only, NAT network
图像识别与检测--笔记
The difference between typescript let and VaR
[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
An overview of IfM Engage
Mail sending of vertx
TreeMap
Go language foundation ----- 07 ----- method
技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建