本文主要是介绍golang基础-终端读(Scanln\bufio)、bufio文件读、、ioutil读读压缩、缓冲区读写、文件写入、文件拷贝,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
-
-
- 终端读写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读读压缩、缓冲区读写、文件写入、文件拷贝的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!