当前位置:网站首页>Write, append, read, and copy of golang files: examples of using bufio packages
Write, append, read, and copy of golang files: examples of using bufio packages
2022-06-30 13:05:00 【Learn programming notes】
golang Writing files 、 Additional 、 Read 、 Copy operation
Go Linguistic os There is a OpenFile function , The prototype is shown below :
func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
among name Is the file name of the file , If you are not running under the current path, you need to add a specific path ;flag Is the processing parameter of the file , by int type , The specific values may vary depending on the system , But the effect is the same .
Here are some common flag File processing parameters :
- O_RDONLY: Open file in read-only mode ;
- O_WRONLY: Write only mode open file ;
- O_RDWR: Open file in read-write mode ;
- O_APPEND: Attach data to the end of the file when writing ( Additional );
- O_CREATE: If it doesn't exist, a new file will be created ;
- O_EXCL: and O_CREATE In combination with , The file must not exist , Otherwise an error is returned ;
- O_SYNC: When doing a series of write operations , Every time I have to wait for the last time I/O When the operation is finished, proceed ;
- O_TRUNC: If possible , Empty file on open .
【 Example 1】: Create a new file golang.txt, And write in it 5 sentence “http://c.biancheng.net/golang/”.
package mainimport ( "bufio" "fmt" "os")func main() { // Create a new file , Write content 5 sentence “http://c.biancheng.net/golang/” filePath := "e:/code/golang.txt" file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Println(" File opening failure ", err) } // Shut down in time file Handle defer file.Close() // When writing a file , Use cached *Writer write := bufio.NewWriter(file) for i := 0; i < 5; i++ { write.WriteString("http://c.biancheng.net/golang/ \n") } //Flush Write the cached file to the file write.Flush()}
After successful execution, a... Will be generated in the specified directory golang.txt file , Open the file as shown in the following figure :
【 Example 2】: Open an existing file , Add content to the original content “C Chinese language network ”
package mainimport ( "bufio" "fmt" "os")func main() { filePath := "e:/code/golang.txt" file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, 0666) if err != nil { fmt.Println(" File opening failure ", err) } // Shut down in time file Handle defer file.Close() // When writing a file , Use cached *Writer write := bufio.NewWriter(file) for i := 0; i < 5; i++ { write.WriteString("C Chinese language network \r\n") } //Flush Write the cached file to the file write.Flush()}
After successful execution , open golang.txt The file discovery content was appended successfully , As shown in the figure below :
【 Example 3】: Open an existing file , Read out the original content , Displayed on the terminal , And add 5 sentence “Hello,C Chinese language network ”.
package mainimport ( "bufio" "fmt" "io" "os")func main() { filePath := "e:/code/golang.txt" file, err := os.OpenFile(filePath, os.O_RDWR|os.O_APPEND, 0666) if err != nil { fmt.Println(" File opening failure ", err) } // Shut down in time file Handle defer file.Close() // Read the contents of the original file , And it's displayed on the terminal reader := bufio.NewReader(file) for { str, err := reader.ReadString('\n') if err == io.EOF { break } fmt.Print(str) } // When writing a file , Use cached *Writer write := bufio.NewWriter(file) for i := 0; i < 5; i++ { write.WriteString("Hello,C Chinese language network . \r\n") } //Flush Write the cached file to the file write.Flush()}
After successful execution , The contents of the file will be printed on the console , And add the specified content to the file , As shown in the figure below :
【 Example 4】: Write a program , Copy the contents of one file to another ( notes : Both files already exist )
package mainimport ( "fmt" "io/ioutil")func main() { file1Path := "e:/code/golang.txt" file2Path := "e:/code/other.txt" data, err := ioutil.ReadFile(file1Path) if err != nil { fmt.Printf(" File opening failure =%v\n", err) return } err = ioutil.WriteFile(file2Path, data, 0666) if err != nil { fmt.Printf(" File opening failure =%v\n", err) }}
After successful execution , The content found has been copied successfully , As shown in the figure below :
Reference link :
http://c.biancheng.net/view/5729.html
边栏推荐
- [yitianxue awk] regular matching
- [learn awk in one day] operator
- kaniko官方文档 - Build Images In Kubernetes
- [one day learning awk] array usage
- Resource realization applet opening traffic main tutorial
- 【精选】资源变现资讯、新闻、自媒体、博客小程序(可引流,开通流量主,带pc后台管理)
- Introduction to the novelty of substrate source code: comprehensive update of Boca system Boca weight calculation, optimization and adjustment of governance version 2.0
- Problems and analysis in JMeter performance testing. How many problems have you encountered?
- 【驚了】迅雷下載速度竟然比不上虛擬機中的下載速度
- 2022-06-23 sail soft part formula and SQL generation (month and quarter retrieval)
猜你喜欢
Matlab tips (22) matrix analysis -- stepwise regression
Determining the subject area of data warehouse construction
How to use AI technology to optimize the independent station customer service system? Listen to the experts!
Rk356x u-boot Institute (command section) 3.3 env related command usage
Machine learning notes - Introduction to autocorrelation and partial autocorrelation
【C】 In depth understanding of pointers and callback functions (Introduction to simulating qsort)
[one day learning awk] use of built-in variables
你想要的异常知识点都在这里了
postman 自動生成 curl 代碼片段
uniapp支付之APP微信支付unicloud版(附源码)
随机推荐
WTM重大更新,多租户和单点登录
JS method of changing two-dimensional array to one-dimensional array
ABAP工具箱 V1.0(附实现思路)
【MySQL】MySQL的安装与配置
Basic syntax of unity script (5) - vector
Derivation of Park transformation formula for motor control
postman 自动生成 curl 代码片段
杭州电子商务研究院:官网(网站)是私域的唯一形态
Definition of variables and assignment of variables in MySQL
Database usage in QT
今日睡眠质量记录80分
Resource realization applet opening traffic main tutorial
Js根据相同值将数组转换为二维数组
Basic syntax of unity script (2) -record time in unity
波卡跨链通信源码探秘: 要素篇
Can the polardb MySQL fees for RDS MySQL data migration be transferred?
Introduction to the renewal of substrate source code: the pledge amount is greatly reduced, and rocksdb can be completely disabled
Determining the subject area of data warehouse construction
【C语言深度解剖】float变量在内存中存储原理&&指针变量与“零值”比较
JMeter's performance test process and performance test focus