终端读写Scanln、Sscanf
package main
import (
"fmt"
)
var (
firstName,lastName,s string
i int
f float32
input = "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 Naegels
fmt.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 main
import (
"bufio"
"fmt"
"os"
)
var inputReader *bufio.Reader
var input string
var err error
func 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: wyf
PS E:\golang\go_pro\src\safly>
bufio文件读(1)
1、os.Open
2、bufio.NewReader
3、reader.ReadString
package main
import (
"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 main
import (
"bufio"
"fmt"
"io"
"os"
)
type CharCount struct {
ChCount int
NumCount int
SpaceCount int
OtherCount int
}
func main() {
file,err := os.Open("output.dat")
if err != nil {
fmt.Println("read file err:",err)
return
}
defer file.Close()
var count CharCount
reader := 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':
fallthrough
case 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 main
import (
"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 main
import (
"bufio"
"compress/gzip"
"fmt"
"os"
)
func main() {
fName := "output.dat.gz"
var r *bufio.Reader
fi,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 main
import (
"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 main
import (
"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,0644)
if err != nil {
fmt.Println("dst open err")
return
}
defer dst.Close()
return io.Copy(dst,src)
}
原文链接:https://www.f2er.com/go/187748.html