当前位置:网站首页>Understand the reading, writing and creation of files in go language
Understand the reading, writing and creation of files in go language
2022-07-04 20:29:00 【1024 questions】
1. Opening and closing of files
1.1 os.open
1.2 os.OpenFile() Open file in specified mode
2. File reading
2.1 Read the data in the file by opening the file
2.2 Use bufio Read the whole line of the file
3. Write file operation
3.1 file.Write And file.WriteString
3.2 bufio.NewWriter
3.3 ioUtil Tool class
1. Opening and closing of files 1.1 os.openos.open Function can open a file call close() Method Close file
// Open file open, err := os.Open("./1.text")if err != nil {// Print exception information fmt.Println("open file err", err)}fmt.Println(" File acquisition completed ")// No exception occurred , Close file open.Close()To prevent forgetting to close the file , Usually, the code to close the file is written in defer in
// Open file open, err := os.Open("./1.text")defer func() {if open != nil {// Close file open.Close()}}()if err != nil {// Print exception information fmt.Println("open file err", err)}fmt.Println(" File acquisition completed ")1.2 os.OpenFile() Open file in specified mode func OpenFile(name string, flag int, perm FileMode) (*File, error) { ...}among :
name: The name of the file to open flag: Open file mode . There are several modes :
| os.O_WRONLY | Just write |
| os.O_CREATE | create a file |
| os.O_RDONLY | read-only |
| os.O_RDWR | Reading and writing |
| os.O_TRUNC | Empty |
| os.O_APPEND | Additional |
perm: File permissions , An octal number .r( read )04,w( Write )02,x( perform )01.
2. File reading 2.1 Read the data in the file by opening the file// First you need to open a file open, err := os.Open("./1.text")defer func() {e := recover()if e != nil {fmt.Println(" An exception occurred when opening the file ", e)}}()if err != nil {// If there is any abnormality There's no need to go down Throw out panic(err)}// If there is no abnormality // establish Byte slice bytes := make([]byte, 1024)defer func() {e := recover()if e != nil {fmt.Println(" An exception occurred while reading the file ", e)}}()for {// Circle reading _, err := open.Read(bytes)if err != nil {panic(err)}// Print the results fmt.Println(string(bytes))}2.2 Use bufio Read the whole line of the file bufio Is in file It encapsulates a layer of API , Support more functions
// Similarly, first open a file file, err := os.Open("./1.text")defer recover()if err != nil {panic(" An exception occurred while opening the file ")}// Encapsulated in the bufioreader := bufio.NewReader(file)defer recover()for {// Read the specified string and change to another line line, _, err := reader.ReadLine()if err != nil {if err == io.EOF {fmt.Println(" The file is read and written ")break}panic(" File reading exception ")}fmt.Println(string(line))}fmt.Println(" End of program running ")func main() {file, err := os.OpenFile("xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)}3. Write file operation Whether it is file reading or file writing You need to open the file first Do it again
3.1 file.Write And file.WriteString// So let's open the file O_RDWR read-write permission O_TRUNC Empty files 0 Start with octal 666 Express Current user Current group Other users Read and write permissions file, err := os.OpenFile("1.text", os.O_RDWR|os.O_TRUNC, 0666)if err != nil {fmt.Printf(" Exception in opening file %v", err)}defer file.Close()// return Bytes written write, err := file.Write([]byte(" Test file write \n"))file.WriteString(" Write the entire string at once ")if err != nil {fmt.Println(err)}fmt.Println(write)3.2 bufio.NewWriter// Based on cache operation file, err := os.OpenFile("2.text", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)if err != nil {panic(err)}defer func() {file.Close()if e := recover(); e != nil {fmt.Printf(" abnormal : Exception in opening file %v", e)}}()// Use bufio Based on cache operation io flow // Need to One io Interface package Writer Interface implementation class and file It's time to Method writer := bufio.NewWriter(file)writer.WriteString(" Write cache string contents 2")// You need to refresh the data in the cache to the hard disk writer.Flush()// Use tool class Open file , Write the file at one go err := ioutil.WriteFile("3.text", []byte(" Tool class writes content "), 0666)if err != nil {fmt.Println(" The program runs abnormally ", err)}This is the article about understanding Go This is the article about reading, writing and creating files in the language , More about Go Language File read and write Please search the previous articles of SDN or continue to browse the relevant articles below. I hope you will support SDN more in the future !
边栏推荐
- Related concepts of federal learning and motivation (1)
- NLP, vision, chip What is the development direction of AI? Release of the outlook report of Qingyuan Association [download attached]
- 公司要上监控,Zabbix 和 Prometheus 怎么选?这么选准没错!
- Qt编写物联网管理平台38-多种数据库支持
- node强缓存和协商缓存实战示例
- 华为nova 10系列支持应用安全检测功能 筑牢手机安全防火墙
- TCP waves twice, have you seen it? What about four handshakes?
- Aiming at the "amnesia" of deep learning, scientists proposed that based on similarity weighted interleaved learning, they can board PNAS
- What should we pay attention to when doing social media marketing? Here is the success secret of shopline sellers!
- 做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
猜你喜欢

解密函数计算异步任务能力之「任务的状态及生命周期管理」

So this is the BGP agreement

什么叫内卷?

Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines

记一次 .NET 某工控数据采集平台 线程数 爆高分析

输入的查询SQL语句,是如何执行的?

NetCore3.1 Json web token 中间件

Employment prospects and current situation of Internet of things application technology

多表操作-内连接查询

Related concepts of federal learning and motivation (1)
随机推荐
Introduction to ACM combination counting
Development and construction of DFI ecological NFT mobile mining system
Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines
Dark horse programmer - software testing - 09 stage 2-linux and database -31-43 instructions issued by modifying the file permission letter, - find the link to modify the file, find the file command,
What are the consequences of closing the read / write channel?
Oracle database, numbers Force 2 decimal places to display-Alibaba Cloud
[in-depth learning] review pytoch's 19 loss functions
六石编程学:关于代码,有六个得意
数据集划分
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
Kotlin inheritance
针对深度学习的“失忆症”,科学家提出基于相似性加权交错学习,登上PNAS
Lingyun going to sea | Murong Technology & Huawei cloud: creating a model of financial SaaS solutions in Africa
【ISMB2022教程】图表示学习的精准医疗,哈佛大学Marinka Zitnik主讲,附87页ppt
Actual combat simulation │ JWT login authentication
ICML 2022 | Meta提出鲁棒的多目标贝叶斯优化方法,有效应对输入噪声
1009 product of polynomials (25 points) (PAT class a)
Write it down once Net analysis of thread burst height of an industrial control data acquisition platform
Cbcgptabwnd control used by BCG (equivalent to MFC TabControl)
太方便了,钉钉上就可完成代码发布审批啦!