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

若有错误,请大佬指出!

相关推荐
Ulyanov34 分钟前
Python实现6-DOF刚体仿真器(下)——环境扰动与控制闭环
开发语言·python·算法·系统仿真·雷达电子对抗·导引头
分布式存储与RustFS38 分钟前
RustFS Beta.10 性能解读:PUT 全面反超 MinIO,Rust 重写对象存储成了?
开发语言·后端·rust
Reart1 小时前
Leetcode 309.买卖股票的最佳时期含冷冻期(你也想成为股票高手吗o〃ω〃o,718)
后端
小小的木头人1 小时前
Python 批量解析 Excel 经纬度,调用高德地图 API 获取中文地址
开发语言·python·excel
Reart1 小时前
Leetcode 188.买卖股票的最佳时机4(718)
后端·算法
Reart1 小时前
Leetcode 123.买卖股票的最佳时期3(内有随心谈,718)
后端·算法
只与明月听2 小时前
LangChain 学习-掌握LangChain Core API
前端·人工智能·后端
nzz_1712142 小时前
PHP程序员转型AI岗位指南:核心技能、北京就业市场与转型路径分析
开发语言·人工智能·php
无相求码2 小时前
数组越界为什么有时候不崩溃?VS2013 下栈上变量的幽灵布局解密
c语言·后端
Risehuxyc2 小时前
C# 将doc转换为docx
开发语言·c#·xhtml