当前位置:网站首页>[go ~ 0 to 1] read, write and create files on the sixth day
[go ~ 0 to 1] read, write and create files on the sixth day
2022-07-04 18:42:00 【Autumn sunset】
1. Opening and closing of files
1.1 os.open
os.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 :
Pattern | meaning |
---|---|
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 bufio
reader := 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)
}
2.3 ioutil Read the entire file at once
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
Use bufio Be sure to call refresh
// 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()
3.3 ioUtil Tool class
// 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)
}
边栏推荐
- VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
- Blue bridge: sympodial plant
- 字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
- Li Kou brush question diary /day8/7.1
- Numpy 的仿制 2
- 如何提高开发质量
- [HCIA continuous update] WAN technology
- The controversial line of energy replenishment: will fast charging lead to reunification?
- Microservice architecture debate between radical technologists vs Project conservatives
- 如何使用 wget 和 curl 下载文件
猜你喜欢
学习路之PHP--phpstudy创建项目时“hosts文件不存在或被阻止打开”
MySQL common add, delete, modify and query operations (crud)
Li Kou brush question diary /day1/2022.6.23
TCP两次挥手,你见过吗?那四次握手呢?
Unity 制作旋转门 推拉门 柜门 抽屉 点击自动开门效果 开关门自动播放音效 (附带编辑器扩展代码)
Scala基础教程--20--Akka
输入的查询SQL语句,是如何执行的?
Journal des problèmes de brosse à boutons de force / day6 / 6.28
Li Kou brush question diary /day4/6.26
VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
随机推荐
Redis master-slave replication
字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
I wrote a learning and practice tutorial for beginners!
SIGMOD’22 HiEngine论文解读
ARTS_ twenty million two hundred and twenty thousand six hundred and twenty-eight
爬虫(6) - 网页数据解析(2) | BeautifulSoup4在爬虫中的使用
提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像
How is the entered query SQL statement executed?
Lua emmylua annotation details
一、C语言入门基础
Halcon模板匹配
[daily question] 871 Minimum refueling times
vbs或vbe如何修改图标
未来几年中,软件测试的几大趋势是什么?
. Net ORM framework hisql practice - Chapter 2 - using hisql to realize menu management (add, delete, modify and check)
Interview summary of large factory Daquan II
线上MySQL的自增id用尽怎么办?
激进技术派 vs 项目保守派的微服务架构之争
The block:usdd has strong growth momentum
[2022 Jiangxi graduate mathematical modeling] curling movement idea analysis and code implementation