天天看點

buf數組寫入html檔案,golang基礎-終端讀(Scanln\bufio)、bufio檔案讀、、ioutil讀讀壓縮、緩沖區讀寫、檔案寫入、檔案拷貝...

終端讀寫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

}

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)

}

總結

如果覺得程式設計之家網站内容還不錯,歡迎将程式設計之家網站推薦給程式員好友。

本圖文内容來源于網友網絡收集整理提供,作為學習參考使用,版權屬于原作者。

小編個人微信号 jb51ccc

喜歡與人分享程式設計技術與工作經驗,歡迎加入程式設計之家官方交流群!