• 终端读写Scanln、Sscanf
  • bufio带缓冲区的读
  • bufio文件读(1)
  • bufio文件读(2)
  • 通过ioutil实现读
  • 读取压缩文件
  • 文件写入
  • 文件拷贝

终端读写Scanln、Sscanf

package mainimport ("fmt"
)var (firstName, lastName, s stringi                      intf                      float32input                  = "56.12 / 5212 / Go"format                = "%f / %d / %s"
)func main() {fmt.Println("Please enter your full name: ")fmt.Scanln(&firstName, &lastName)fmt.Printf("Hi %s %s!\n", firstName, lastName) // Hi Chris Naegelsfmt.Sscanf(input, format, &f, &i, &s)fmt.Println("From the string we read: ", f, i, s)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
Please enter your full name:
hello go lagn
Hi hello go!
From the string we read:  56.12 5212 Go
PS E:\golang\go_pro\src\safly>

func Sscanf
func Sscanf(str string, format string, a …interface{}) (n int, err error)
Scanf 扫描实参 string,并将连续由空格分隔的值存储为连续的实参, 其格式由 format 决定。它返回成功解析的条目数。

func Scanln
func Scanln(a …interface{}) (n int, err error)
Scanln 类似于 Scan,但它在换行符处停止扫描,且最后的条目之后必须为换行符或 EOF。

bufio带缓冲区的读

ReadString读取换行
func (*Reader) ReadString
func (b *Reader) ReadString(delim byte) (line string, err error)
ReadString读取输入到第一次终止符发生的时候,返回的string包含从当前到终止符的内容(包括终止符)。 如果ReadString在遇到终止符之前就捕获到一个错误,它就会返回遇到错误之前已经读取的数据,和这个捕获 到的错误(经常是 io.EOF)。当返回的数据没有以终止符结束的时候,ReadString返回err != nil。 对于简单的使用,或许 Scanner 更方便。

package mainimport ("bufio""fmt""os"
)var inputReader *bufio.Reader
var input string
var err errorfunc main() {inputReader = bufio.NewReader(os.Stdin)fmt.Println("Please enter some input: ")input, err = inputReader.ReadString('\n')if err == nil {fmt.Printf("The input was: %s\n", input)}
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
Please enter some input:
wyf
The input was: wyfPS E:\golang\go_pro\src\safly>

bufio文件读(1)

1、os.Open
2、bufio.NewReader
3、reader.ReadString

package mainimport ("bufio""fmt""os"
)func main() {file, err := os.Open("‪output.dat")if err != nil {fmt.Println("read file err:", err)return}defer file.Close()reader := bufio.NewReader(file)str, err := reader.ReadString('\n')if err != nil {fmt.Println("read string failed, err:", err)return}fmt.Printf("read str succ, ret:%s\n", str)
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
read file err: open ‪test: The system cannot find the file specified.
PS E:\golang\go_pro\src\safly>

运行结果有问题,但是找不出问题所在

bufio文件读(2)

练习,从终端读取一行字符串,统计英文、数字、空格以及其他字符的数量。

package mainimport ("bufio""fmt""io""os"
)type CharCount struct {ChCount    intNumCount   intSpaceCount intOtherCount int
}func main() {file, err := os.Open("output.dat")if err != nil {fmt.Println("read file err:", err)return}defer file.Close()var count CharCountreader := bufio.NewReader(file)for {str, err := reader.ReadString('\n')//读取完毕if err == io.EOF {break}//读取失败if err != nil {fmt.Printf("read file failed, err:%v", err)break}/*一个字符串可以可以用一个rune(又名int32)数组来表示,每个rune都表示一个单一的字符。如:*/runeArr := []rune(str)for _, v := range runeArr {switch {case v >= 'a' && v <= 'z':fallthroughcase v >= 'A' && v <= 'Z':count.ChCount++case v == ' ' || v == '\t':count.SpaceCount++case v >= '0' && v <= '9':count.NumCount++default:count.OtherCount++}}}fmt.Printf("char count:%d\n", count.ChCount)fmt.Printf("num count:%d\n", count.NumCount)fmt.Printf("space count:%d\n", count.SpaceCount)fmt.Printf("other count:%d\n", count.OtherCount)
}

通过ioutil实现读

package mainimport ("fmt""io/ioutil""os"
)func main() {inputFile := "products.txt"outputFile := "products_copy.txt"buf, err := ioutil.ReadFile(inputFile)if err != nil {fmt.Fprintf(os.Stderr, "File Error: %s\n", err)return}fmt.Printf("%s\n", string(buf))err = ioutil.WriteFile(outputFile, buf, 0x644)if err != nil {panic(err.Error())}
}

在项目下创建2个文件

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
sfds
PS E:\golang\go_pro\src\safly>

读取压缩文件

1、os.Open压缩文件
2、gzip.NewReader(fi)
3、bufio.NewReader(fz)
4、bufio.ReadString

package mainimport ("bufio""compress/gzip""fmt""os"
)
func main() {fName := "output.dat.gz"var r *bufio.Readerfi, err := os.Open(fName)if err != nil {fmt.Fprintf(os.Stderr, "%v, Can’t open %s: error: %s\n", os.Args[0], fName, err)os.Exit(1)}fz, err := gzip.NewReader(fi)if err != nil {fmt.Fprintf(os.Stderr, "open gzip failed, err: %v\n", err)return}r = bufio.NewReader(fz)for {line, err := r.ReadString('\n')if err != nil {fmt.Println("Done reading file")os.Exit(0)}fmt.Println(line)}
}

输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!Done reading file
PS E:\golang\go_pro\src\safly>

文件写入

文件写入
1、OpenFile打开文件(没有文件就创建)
1、创建bufio.NewWriter对象
2、WriteString写入操作
3、刷新Flush

package mainimport ("bufio""fmt""os"
)func main() {outputFile, outputError := os.OpenFile("output.dat",
os.O_WRONLY|os.O_CREATE, 0666)if outputError != nil {fmt.Printf("An error occurred with file creation\n")return}defer outputFile.Close()outputWriter := bufio.NewWriter(outputFile)outputString := "hello world!\n"for i := 0; i < 10; i++ {outputWriter.WriteString(outputString)}outputWriter.Flush()
}

文件拷贝

简单的三步骤
1、 os.Open(srcName)
2、os.OpenFile
3、io.Copy(dst, src)

package mainimport ("fmt""io""os"
)func main() {CopyFile("target.txt", "source.txt")fmt.Println("Copy done!")
}func CopyFile(dstName, srcName string) (written int64, err error) {src, err := os.Open(srcName)if err != nil {fmt.Println("src open err")return}defer src.Close()dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)if err != nil {fmt.Println("dst open err")return}defer dst.Close()return io.Copy(dst, src)
}

golang基础-终端读(Scanln\bufio)、bufio文件读、、ioutil读读压缩、缓冲区读写、文件写入、文件拷贝相关推荐

  1. Python程序员经常会遇到文件权限问题,例如在打开或写入文件时出现“PermissionError: [Errno 13] Permission denied...

    Python程序员经常会遇到文件权限问题,例如在打开或写入文件时出现"PermissionError: [Errno 13] Permission denied"错误.这个错误通常 ...

  2. ecplice中class.forname一直报错_Python怎么把文件内容读取出来,怎么把内容写入文件中

    读写文件是最常见的IO操作.Python内置了读写文件的函数. Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 ...

  3. python异步写文件_结合异步http请求将数据写入文件

    我从here编辑了此代码:import asyncio import time from aiohttp import ClientPayloadError from aiohttp import C ...

  4. java 多进程写一个文件_java高并发多线程及多进程同时写入文件研究

    测试&思考: 环境:windows 七.linux centos 6.三.java8html java多线程同时写一个文件 java高并发环境下多线程同时写入一个文件时, 经过 FileLoc ...

  5. java 写文件 属性吗_使用JAVA读写Properties属性文件

    自己定义一个属性文件:例如prop.properties baseFilePath=D\:/kuanter/resource tesx=abcd 我们要做的第一步就是要将文件读取到Properties ...

  6. php接收post写入文件,PHP中Post和Get获取数据写入文件中

    有时候Post或者Get传过来的数据我们不知道它是个什么样的形式,它可能是JSON格式或者就是简单提交过来的数据,这时候我们可以把他写入到文本中,就可以看到传过来的数据是什么格式了. $val = & ...

  7. java如何解压rar文件怎么打开,Java压缩与解压rar文件

    package com.sunz.fileUpload; public class RarToFile { //cmd 压缩与解压缩命令 private static String rarCmd = ...

  8. python列表写入txt文件中文乱码,python 字典格式的文本写入文件,中文乱码(Unicode)的问题...

    最近在做命名实体识别,需要处理数据,将字典格式的标记文本写入文件 然后一搜发现可以变成json再write到文件里(json.dumps),一试发现中文全部变成Unicode格式,又查如何变成中文.. ...

  9. c语言将数据写入文件后乱码_c语言,数据能写入文件,但是从文件读取数据的时候,出现了乱码,如下代码,求解答...

    //写入数据代码#include#defineSIZE2typedefstructstu1//学生信息表{charname[10];intnum;intage;charaddr[15];}studen ...

最新文章

  1. 为增进理解力而奋斗终身
  2. Webview页面的控件元素定位
  3. 线性方程组与基尔霍夫定律
  4. CapsLock魔改大法——变废为宝实现高效编辑
  5. ASP.NET 2.0运行时简要分析
  6. 计算机硬件技术基础5章在线,《计算机硬件技术基础》试题(D)
  7. mitmproxy https抓包的原理是什么?
  8. 漫步最优化四十——Powell法(上)
  9. OFDM系统MATLAB仿真
  10. 【OpenCV】绘制简单图形
  11. Ubuntu下安装并配置VS Code编译C++
  12. java 实现用户登陆代码_Java Web用户登录实例代码
  13. java报错stderr_struts2 文件上传路径错误 ERROR [STDERR] java.io.FileNotFoundException:
  14. 单循环赛 贝格尔编排法实现
  15. linux系统的wps办公软件,linux上安装wps办公软件
  16. 微信小程序的事件大全
  17. 商业发掘 - 苹果 IOS 充值代充,充值卡为什么会便宜,以及其中的一些门道
  18. xaxis python_Python中的分组Xaxis可变性图
  19. 未睹棺椁先哭君——谷歌墓志铭
  20. 使用BDE数据库引擎的应用软件出现Insufficient disk space的解决方法

热门文章

  1. 史上争议最大的一本Java书籍,到底值不值得我们一读?
  2. Linux重要指令讲解
  3. 春运期间国航将加飞进出成都航班406班次 增座超十万个
  4. 腾讯云人脸核身uniapp+后端代码
  5. 图像清晰度识别之Laplacian算子
  6. 网络安全知识:APT攻击是什么意思?APT攻击防御措施
  7. pytorch中的kl divergence计算问题
  8. 欢迎使用 MWeb-Test
  9. FX3U_定位控制_硬件连接
  10. CVE-2020-1938漏洞复现(文末附EXP代码)