【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)
}

若有错误,请大佬指出!

相关推荐
小码哥_常5 小时前
解锁AI编程密码:程序员常用的10个AI提示词
后端
九转成圣6 小时前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
SmartRadio6 小时前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信
开发语言·网络·智能手机·esp32·长距离wifi
laowangpython6 小时前
Rust 入门:GitHub 热门内存安全编程语言
开发语言·其他·rust·github
我叫汪枫6 小时前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch6 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI6 小时前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn
Brendan_0016 小时前
JavaScript的Stomp.over
开发语言·javascript·ecmascript
念2346 小时前
f5 shape分析
开发语言·javascript·ecmascript
苍穹之跃6 小时前
某量JS逆向
开发语言·javascript·ecmascript