当前位置:网站首页>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 .
边栏推荐
- TreeMap
- Use of other streams
- Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing
- Vertx's responsive MySQL template
- Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction
- Technical dry goods Shengsi mindspire operator parallel + heterogeneous parallel, enabling 32 card training 242 billion parameter model
- 技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer
- 论文学习——鄱阳湖星子站水位时间序列相似度研究
- Leetcode 198: 打家劫舍
- Introduction of transformation flow
猜你喜欢

技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验

c语言指针的概念

PAT甲级 1029 Median

Lucene skip table

技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!

Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction
![PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef](/img/65/1f28071fc15e76abb37f1b128e1d90.jpg)
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef

URL programming

Summary of Arduino serial functions related to print read

Common methods of file class
随机推荐
Usage of requests module
技术干货|关于AI Architecture未来的一些思考
Custom generic structure
Lucene merge document order
Understanding of class
专题 | 同步 异步
The embodiment of generics in inheritance and wildcards
技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer
研究显示乳腺癌细胞更容易在患者睡觉时进入血液
Leetcode 213: looting II
PAT甲级 1031 Hello World for U
Longest common prefix and
List exercises after class
论文学习——鄱阳湖星子站水位时间序列相似度研究
PgSQL converts string to double type (to_number())
Reconnaissance et détection d'images - Notes
【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
Rabbit MQ message sending of vertx
Vertx's responsive redis client
Use of file class