golang学习笔记 ----读写文件
使用io/ioutil进行读写文件
ioutil包
其中提到了两个方法:
func ReadFile
func ReadFile(filename string) ([]byte, error)
ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.
func WriteFile
func WriteFile(filename string, data []byte, perm os.FileMode) error
WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm; otherwise WriteFile truncates it before writing
读文件:
package main import (
"fmt"
"io/ioutil"
) func main() {
b, err := ioutil.ReadFile("test.log")
if err != nil {
fmt.Print(err)
}
fmt.Println(b)
str := string(b)
fmt.Println(str)
}
写文件:
package main import (
"io/ioutil"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() { d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("test.txt", d1, 0644)
check(err)
}
使用os进行读写文件
os包
首先要注意的就是两个打开文件的方法:
func Open
func Open(name string) (*File, error)
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.
读文件:
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
func OpenFile
需要提供文件路径、打开模式、文件权限
func OpenFile(name string, flag int, perm FileMode) (*File, error)
OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.
读文件:
package main import (
"log"
"os"
) func main() {
f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
读方法
package main import (
"bufio"
"fmt"
"io"
"os"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() { f, err := os.Open("foo.dat")
check(err) b1 := make([]byte, 5)
n1, err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1)) o2, err := f.Seek(6, 0)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2)) o3, err := f.Seek(6, 0)
check(err)
b3 := make([]byte, 2)
n3, err := io.ReadAtLeast(f, b3, 2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3)) _, err = f.Seek(0, 0)
check(err) r4 := bufio.NewReader(f)
b4, err := r4.Peek(5)
check(err)
fmt.Printf("5 bytes: %s\n", string(b4)) f.Close() }
写方法
package main import (
"bufio"
"fmt"
"os"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() { f, err := os.Create("/tmp/dat2")
check(err) defer f.Close() d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
check(err)
fmt.Printf("wrote %d bytes\n", n2) n3, err := f.WriteString("writes\n")
fmt.Printf("wrote %d bytes\n", n3) f.Sync() w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4) w.Flush() }
几种读取文件方法速度比较
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
func read0(path string) string {
f, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("%s\n", err)
panic(err)
}
return string(f)
}
func read1(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := fi.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if 0 == n {
break
}
chunks = append(chunks, buf[:n]...)
}
return string(chunks)
}
func read2(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
r := bufio.NewReader(fi)
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if 0 == n {
break
}
chunks = append(chunks, buf[:n]...)
}
return string(chunks)
}
func read3(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
fd, err := ioutil.ReadAll(fi)
return string(fd)
}
func main() {
file := "foo.dat"
start := time.Now()
read0(file)
t0 := time.Now()
fmt.Printf("Cost time %v\n", t0.Sub(start))
read1(file)
t1 := time.Now()
fmt.Printf("Cost time %v\n", t1.Sub(t0))
read2(file)
t2 := time.Now()
fmt.Printf("Cost time %v\n", t2.Sub(t1))
read3(file)
t3 := time.Now()
fmt.Printf("Cost time %v\n", t3.Sub(t2))
}
golang学习笔记 ----读写文件的更多相关文章
- Linux系统学习笔记:文件I/O
Linux支持C语言中的标准I/O函数,同时它还提供了一套SUS标准的I/O库函数.和标准I/O不同,UNIX的I/O函数是不带缓冲的,即每个读写都调用内核中的一个系统调用.本篇总结UNIX的I/O并 ...
- golang学习笔记19 用Golang实现以太坊代币转账
golang学习笔记19 用Golang实现以太坊代币转账 在以太坊区块链中,我们称代币为Token,是以太坊区块链中每个人都可以任意发行的数字资产.并且它必须是遵循erc20标准的,至于erc20标 ...
- golang学习笔记12 beego table name `xxx` repeat register, must be unique 错误问题
golang学习笔记12 beego table name `xxx` repeat register, must be unique 错误问题 今天测试了重新建一个项目生成新的表,然后复制到旧的项目 ...
- golang学习笔记8 beego参数配置 打包linux命令
golang学习笔记8 beego参数配置 打包linux命令 参数配置 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/docs/mvc/contro ...
- golang学习笔记7 使用beego swagger 实现API自动化文档
golang学习笔记7 使用beego swagger 实现API自动化文档 API 自动化文档 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/doc ...
- golang学习笔记6 beego项目路由设置
golang学习笔记5 beego项目路由设置 前面我们已经创建了 beego 项目,而且我们也看到它已经运行起来了,那么是如何运行起来的呢?让我们从入口文件先分析起来吧: package main ...
- golang学习笔记5 用bee工具创建项目 bee工具简介
golang学习笔记5 用bee工具创建项目 bee工具简介 Bee 工具的使用 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/docs/instal ...
- go语言,golang学习笔记4 用beego跑一个web应用
go语言,golang学习笔记4 用beego跑一个web应用 首页 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/ 更新的命令是加个 -u 参数,g ...
- go语言,golang学习笔记2 web框架选择
go语言,golang学习笔记2 web框架选择 用什么go web框架比较好呢?能不能推荐个中文资料多的web框架呢? beego框架用的人最多,中文资料最多 首页 - beego: 简约 & ...
随机推荐
- LintCode: Delete Node in the Middle of Singly Linked List
开始没看懂题目的意思,以为是输入一个单链表,删掉链表中间的那个节点. 实际的意思是,传入的参数就是待删节点,所以只要把当前节点指向下一个节点就可以了. C++ /** * Definition of ...
- SQL 之 查询操作重复记录
有时,我们的数据表中会存在一些冗余数据,这就要求我们查询并操作这些冗余数据. 一.查询表中重复记录 例如,查找重复记录是根据单个字段(peopleId)来判断 SELECT * FROM Tpeopl ...
- [置顶] 在Visual Studio 2008上调试C语言程序
C语言的地位和重要性就不用说了,但,很多人学习C语言,还在使用Visual C++ 6.0,甚至还有人使用Turbo C,很无语,只说一句吧:“OUT了". 让我们体验一下华丽的Visual ...
- spring Ioc 实践
了解过IoC的概念,没有真正实践,感觉还是会比较模糊.自己的实践虽然简单,但还是记录下呀~ 1. 通过注解的方式注入service 1.1 controller中创建对象 @Controller @R ...
- [转]Maven介绍,包括作用、核心概念、用法、常用命令、扩展及配置
转自:http://www.trinea.cn/android/maven/ 两年半前写的关于Maven的介绍,现在看来都还是不错的,自己转下.写博客的一大好处就是方便自己以后查阅,自己总结的总是最靠 ...
- PC版收音机—龙卷风收音机
龙卷风收音机-龙卷风 文章来源:刘俊涛的博客 欢迎关注,有问题一起学习欢迎留言.评论
- LLVM lli llc
http://zke1ev3n.me/2016/01/18/%E5%9F%BA%E4%BA%8ELLVM%E7%9A%84%E4%BB%A3%E7%A0%81%E6%B7%B7%E6%B7%86/ h ...
- django之创建第7个项目-url配置
1.配置urls.py from django.conf.urls import patterns, include, url #Uncomment the next two lines to ena ...
- code vs 2597 团伙
题目描述 Description 1920年的芝加哥,出现了一群强盗.如果两个强盗遇上了,那么他们要么是朋友,要么是敌人.而且有一点是肯定的,就是: 我朋友的朋友是我的朋友: 我敌人的敌人也是我的朋友 ...
- URI -URL-URN区别
URI -URL-URN区别 URI (uniform resource identifier) 统一资源标识符,用来唯一的标识一个资源URL(uniform resource locator) ...