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

若有错误,请大佬指出!

相关推荐
Demon--hx26 分钟前
[C++]迭代器
开发语言·c++
倚肆34 分钟前
Spring Boot 中的 Bean 与自动装配详解
spring boot·后端·python
BanyeBirth35 分钟前
C++窗口问题
开发语言·c++·算法
q***06291 小时前
PHP进阶-在Ubuntu上搭建LAMP环境教程
开发语言·ubuntu·php
g***96902 小时前
【Spring Boot 实现 PDF 导出】
spring boot·后端·pdf
charlie1145141912 小时前
从 0 开始:在 WSL + VSCode 上利用 Maven 构建 Java Spring Boot 工程
java·笔记·vscode·后端·学习·maven·springboot
k***3883 小时前
SpringBoot Test详解
spring boot·后端·log4j
z***89714 小时前
SpringBoot Maven 项目 pom 中的 plugin 插件用法整理
spring boot·后端·maven
郝学胜-神的一滴5 小时前
Qt的QSlider控件详解:从API到样式美化
开发语言·c++·qt·程序人生
学困昇5 小时前
C++11中的{}与std::initializer_list
开发语言·c++·c++11