首页 > 其他分享 >Golang初学:文件操作,标准库

Golang初学:文件操作,标准库

时间:2024-05-15 22:32:34浏览次数:22  
标签:文件 fdst err Golang 初学 fsrc File os

go version go1.22.1 windows/amd64

Windows 11 + amd64

x86_64 x86_64 GNU/Linux

---

 

序章

读取文件内容,写入新文件(可能存在、也可能不存在)。

 

相关标准库

  • io
  • fs
  • os
  • path
  • filepath

 

Show Code

func CopyFile() {
	// 测试文件拷贝

	var fsrc, fdst string
	var start time.Time

	fsrc = "D:/test/fs01.go"
	fdst = "D:/test/fs01.go.bak"

	start = time.Now()
	copyFromTo(fsrc, fdst)
	fmt.Println(fsrc, "耗时:", time.Now().Sub(start))

	// 第二次测试时,文件已存在
	copyFromTo(fsrc, fdst)

	fsrc = "D:/test/VTS_01_1.VOB"
	fdst = "D:/test/VTS_01_1.VOB.bak"
	start = time.Now()
	copyFromTo(fsrc, fdst)
	fmt.Println(fsrc, "耗时:", time.Now().Sub(start))

	copyFromTo(fsrc, fdst)
}


// 拷贝文件 fsrc 到 fdst
func copyFromTo(fsrc, fdst string) {
	fsrcp := openFileSrc(fsrc)
	fdstp := openFileDstForWrite(fdst)

	copyFileData(fsrcp, fdstp)

}

// 打开文件:只读 os.Open(.)
// 错误时退出程序
func openFileSrc(path string) (fr *os.File) {
	fr, err := os.Open(path)
	if err != nil {
		log.Fatal(err)
	}

	return
}

// 打开文件:可读写
// 不存在,先新建
// 已存在,先清空
// 返回 fw
func openFileDstForWrite(path string) (fw *os.File) {
	// 这里的 参数2、参数3 还有不同的配置
	fw, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		log.Fatal(err)
	}

	return
}

// 拷贝文件数据
func copyFileData(fsrcp, fdstp *os.File) {
	// 缓冲区:字节分片
	var buf = make([]byte, 1024)

	var rc int
	var rerr error
	var testTotal int
	for {
		if rc, rerr = fsrcp.Read(buf); rerr == nil {
			// 已读取 rc 字节到 buf
			// 写入 fdstp
			fdstp.Write(buf[:rc])
			testTotal += rc
		} else if rerr == io.EOF {
			log.Println("写入文件数据成功...结束。", rerr, "testTotal=", testTotal)
			break
		} else {
			log.Fatal("写入文件数据失败...", rerr)
		}
	}
}

 

官文资料

std: os 文件打开 函数

// https://pkg.go.dev/[email protected]

/*
Open opens the named file for reading. 
If successful, methods on the returned file can be used for reading; 
the associated file descriptor has mode O_RDONLY. 
If there is an error, it will be of type *PathError.
*/
func Open(name string) (*File, error)

/*
OpenFile is the generalized open call; most users will use Open or Create instead.
示例:
f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644)
*/
func OpenFile(name string, flag int, perm FileMode) (*File, error)

注意,这里的 flag、perm 参数设置很关键。

 

std:os 文件读取、写入 方法——*File 的方法

/*
Read reads up to len(b) bytes from the File and stores them in b. 
It returns the number of bytes read and any error encountered. 
At end of file, Read returns 0, io.EOF.
*/
func (f *File) Read(b []byte) (n int, err error)
// 注意,返回的 err 为 io.EOF 也是成功,表示结束,需要 退出读取

/*
Write writes len(b) bytes from b to the File. 
It returns the number of bytes written and an error, if any. 
Write returns a non-nil error when n != len(b).
*/
func (f *File) Write(b []byte) (n int, err error)
// 注意,参数 b 不一定是读取 全部字节,因此,代码里使用了 buf[:rc]

 

测试

结果:成功。

2024/05/15 21:01:51 写入文件数据成功...结束。 EOF testTotal= 299
D:/test/fs01.go 耗时: 20.9464ms
2024/05/15 21:01:51 写入文件数据成功...结束。 EOF testTotal= 299
2024/05/15 21:01:52 写入文件数据成功...结束。 EOF testTotal= 24037376
D:/test/VTS_01_1.VOB 耗时: 143.7081ms
2024/05/15 21:01:52 写入文件数据成功...结束。 EOF testTotal= 24037376

截图:

 

END.

ben发布于博客园

本文链接:

https://www.cnblogs.com/luo630/p/18194645

ben发布于博客园

参考资料

1、golang 相关 std

https://pkg.go.dev/std

2、

 

ben发布于博客园

ben发布于博客园

 

标签:文件,fdst,err,Golang,初学,fsrc,File,os
From: https://www.cnblogs.com/luo630/p/18194645

相关文章

  • Linux-文件操作实践-2
    #昨日回顾什么是环境变量1.环境2.变量环境,你的系统的运行环境,如windows,linux来看看linux中的,环境变量有哪些以及它的作用是什么?变量是有作用的1.自定义变量1.变量的作用[root@fjh001~]#cathello.shname="隔壁的老张"echo"你好$name"echo"吃了吗$name"......
  • 爬虫-JSON文件存储
    JSON文件存储JSON是一种轻量级的数据交换格式,它是基于ECMAScript的一个子集;JSON在Python中分别由list和dict组成;1、JSON模块的功能函数描述json.dumps()将python类型转换为字符串,返回一个str对象。实现把一个python对象编码转换成JSON字符串json.loads()把JSO......
  • 爬虫-CSV文件存储
    CSV文件存储CSV是CommaSeparatedValues,称为逗号分隔值,一种以.csv结尾的文件,所有值都是字符串。文件操作示例importcsvwithopen('student.csv','a+',newline='')asfile:#newline=''表示不空行#创建一个writer对象writer=csv.writer(file)#一次写......
  • Linux基础-文件特殊权限
    #day13今日安排默写昨日作业讲解文件权限篇综合知识脑图特殊权限(了解)linux提供的12个特殊权限默认的9位权限rwxrwxrwx还有三个隐藏的特殊权限,如下suid比如/usr/bin/passwdsgidsbit特殊权限对照表类别suidsgidsticky字符表示......
  • Adobe ColdFusion 任意文件读取漏洞
    漏洞描述由于AdobeColdFusion的访问控制不当,未经身份认证的远程攻击者可以构造恶意请求读取目标服务器上的任意文件,泄露敏感信息。Fofa:app="Adobe-ColdFusion"&&title=="ErrorOccurredWhileProcessingRequest"POC通过特定的ColdFusion管理端点获取UUIDGET/CFIDE/ad......
  • 【django学习-28】列表界面模板下载与上传文件
    前言,我们在实际项目开发过程中,经常有列表界面,有上传功能,并且支持先下载模板,后上传1.实现效果与前端展示<formmethod="post"enctype="multipart/form-data"action="/depart/multi/">{%csrf_token%}<divclass="form-group"><inputtyp......
  • 【django学习-27】media介绍与文件上传
    前言:django开发过程中,有2个文件夹(也即:目录)比较特殊:static文件夹(目录)、media文件夹(目录)。static目录:我们项目自己用到的文件(css、js、项目图片、插件),建议放在static目录下。media目录:用户自己上传的文件等资源,建议放在media目录下。要想用media目录,必须先配置启用它。1.me......
  • yaml(yml)与properties文件的区别
    SpringBoot支持两种格式的配置文件,一种是yml,而另一种就是properties,默认的文件名为application.yml或者.propertiesproperties配置文件:key=value;yml配置文件key:value;yml更好的配置多种数据类型配置对象数据类型:student:id:1name:zhangsanage:18......
  • 使用playwright控制浏览器在服务器端将网页转化为PDF文件
    需求在实际需要中,经常存在需要在服务器端将网页转化为PDF文件保存下来。代码requirements.txt点击查看代码playwrightconvert_pdf.py点击查看代码fromplaywright.sync_apiimportsync_playwright,Playwrightimportargparsedefrun(playwright:Playwright,url......
  • 如何把 log4net.config 文件删除, 改成代码实现
    如何把log4net.config文件改成代码?这样在编写winform或者其他客户端的时候就省去了一个配置文件分享下我常用的log4net.config配置文件<?xmlversion="1.0"encoding="utf-8"?><configuration><!--<configSections><sectionname="log4net"typ......