1. 基础
str := fmt.Sprintf("num is %f", 3.1415926)
fmt.Fprintln(os.Stdout, "hello\n")
2. 结构体输出
type Data struct {
}
func (self Data) String() string {
return "data"
}
3. 基本的IO接口
func ReadFrom(reader io.Reader, num int) ([]byte, error) {
p := make([]byte, num)
n, err := reader.Read(p)
if n > 0 {
return p[:n], nil
}
return p, err
}
data, _ := ReadFrom(strings.NewReader("Helloworld", 12))
命令行读取输入
data, _ := ReadFrom(os.Stdin, 11)
文件中读取
file, _ := os.Open("main.go")
defer file.Close()
data, _ = ReadFrom(file, 9)
缓冲IO
strReader := strings.NewReader("helloworld")
bufReader := bufio.NewReader(strReader)
data, _ := bufReader.Peek(5) //返回缓冲区的5个字节
i := bufReader.Buffered() //返回缓冲区缓冲了多少个字节
str, _ := bufReader.ReadString(' ') //利用空格切割,返回string
//写
w := bufio.NewWriter(os.stdOut)
fmt.Fprint(w, "Hello ")
w.Flush() //刷新缓冲
统计文件行数
func main() {
if len(os.Args) < 2 {
return
}
filename := os.Args[1]
file, _ := op.Open(filename)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
reader := bufio.NewReader(file)
line := 0
for {
_,isPrefix,err := reader.ReadLine()
if err != nil {
break
}
if !isPrefix {//如果一行过长的时候isPrefix == true
line++
}
}
}
二进制文件的读取
//图片
img, _ := os.Open("image.png")
defer img.Close()
var headA,headB byte
binary.Read(img, binary.BigEndian, &headA )
binary.Read(img, binary.BigEndian, &headB )
var size uint32
binary.Read(img, binary.BigEndian, &size )
var reversedA, reversedB uint16
binary.Read(img, binary.BigEndian, &reversedA )
binary.Read(img, binary.BigEndian, &reversedA )
var offbits uint32
binary.Read(img, binary.BigEndian, &offbits )
利用struct读取文件头
type bitmapHeader struct {
Size uint32
Width int32
Height int32
Places uint16
BitCount uint16
Compression uint32
SizeImage uint32
XperlsPerMeter int32
YperlsPerMeter int32
ClsrUsed uint32
ClrImportant uint32
}
bitmapInfoHeader := new(bitmapHeader)
binry.Read(image, binary.BigEndian, bitmapInfoHeader)