【Golang】I/O操作

I/O接口源码:

Go 复制代码
type Reader interface {
	Read(p []byte) (n int, err error)
}
type Writer interface {
	Write(p []byte) (n int, err error)
}

一、标准I/O

从标准输入中读取数据:

NewReader需要传入一个实现了Reader接口的类,os.Sdtin的类型为*File,这个类实现了Reader接口,使用以下命令查看源码文档:

bash 复制代码
$ go doc os.File

os.Stdin对应1号文件描述符的文件,从标准输入读取数据:

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	buf := bufio.NewReader(os.Stdin)
	line, err := buf.ReadString('\n')
	if err != nil {
		fmt.Println("read Stdio error :", err)
	}
	fmt.Println("buf :", line)

}

输出数据到标准输出:

与标准输入同理

Go 复制代码
package main

import (
	"bufio"
	"os"
)

func main() {
	buf := bufio.NewWriter(os.Stdout)
	buf.Write([]byte("hello world"))
	buf.Flush()
}

二、文件I/O

使用IO标准库:

Go 复制代码
package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	file, _ := os.Open("./text.txt")
	defer file.Close()
	buf, _ := io.ReadAll(file)
	fmt.Println("file context :", string(buf))
}
Go 复制代码
package main

import (
	"io"
	"os"
)

func main() {
	file, _ := os.OpenFile("./text.txt", os.O_WRONLY|os.O_TRUNC, os.ModePerm)
	defer file.Close()
	io.WriteString(file, "ni hao")
}

三、网络I/O

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"net"
)

func main() {
	listener, _ := net.Listen("tcp", "127.0.0.1:1234")
	defer listener.Close()
	conn, _ := listener.Accept()
	conn.Write([]byte("hello world"))

	buf := bufio.NewReader(conn)
	line, _ := buf.ReadString('\n')
	fmt.Println("recv :", line)
}

若有错误,请大佬指出!

相关推荐
万粉变现经纪人3 小时前
如何解决 pip install -r requirements.txt 私有索引未设为 trusted-host 导致拒绝 问题
开发语言·python·scrapy·flask·beautifulsoup·pandas·pip
qq_479875433 小时前
C++ std::Set<std::pair>
开发语言·c++
毕业设计制作和分享3 小时前
springboot150基于springboot的贸易行业crm系统
java·vue.js·spring boot·后端·毕业设计·mybatis
云知谷5 小时前
【C++基本功】C++适合做什么,哪些领域适合哪些领域不适合?
c语言·开发语言·c++·人工智能·团队开发
l1t6 小时前
DeepSeek辅助利用搬移底层xml实现快速编辑xlsx文件的python程序
xml·开发语言·python·xlsx
你的人类朋友7 小时前
【Node】认识multer库
前端·javascript·后端
C_Liu_8 小时前
C++:list
开发语言·c++
my rainy days8 小时前
C++:友元
开发语言·c++·算法
小梁努力敲代码8 小时前
java数据结构--List的介绍
java·开发语言·数据结构
云知谷8 小时前
【HTML】网络数据是如何渲染成HTML网页页面显示的
开发语言·网络·计算机网络·html