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

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/os@go1.22.3

/*
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发布于博客园

 

posted @ 2024-05-15 22:22  快乐的凡人721  阅读(6)  评论(0编辑  收藏  举报